Search code examples
rvectorconcatenationpaste

Combine multiple paste0 to one paste0


I am creating vectors of different length using paste0() and concatenating to one vector:

c(
paste0("A_", 1:16),
paste0("B_", 1:12),
paste0("C_", 3:6),
paste0("D_3_4_C_1_2"),
paste0("E_", rep(1:2, 4), "_", rep(1:4, each=2))
)
 [1] "A_1"         "A_2"         "A_3"         "A_4"         "A_5"         "A_6"         "A_7"         "A_8"        
 [9] "A_9"         "A_10"        "A_11"        "A_12"        "A_13"        "A_14"        "A_15"        "A_16"       
[17] "B_1"         "B_2"         "B_3"         "B_4"         "B_5"         "B_6"         "B_7"         "B_8"        
[25] "B_9"         "B_10"        "B_11"        "B_12"        "C_3"         "C_4"         "C_5"         "C_6"        
[33] "D_3_4_C_1_2" "E_1_1"       "E_2_1"       "E_1_2"       "E_2_2"       "E_1_3"       "E_2_3"       "E_1_4"      
[41] "E_2_4"      

My question is: In a scenario where multiple vectors should be created, is it possible to combine all the paste0 to one paste0:

Desired output: Something like paste0(("A_", 1:16), ("B_", 1:12)) -> which does not work!!!

update: Desired output Something like this non working code: Note I removed 4 paste0()

c(
paste0("A_", 1:16),
      ("B_", 1:12),
      ("C_", 3:6),
      ("D_3_4_C_1_2"),
      ("E_", rep(1:2, 4), "_", rep(1:4, each=2))
)

Solution

  • Here is another approach using do.call and a nested list:

    args <- list(
      list("A_", 1:16),
      list("B_", 1:12),
      list("C_", 3:6),
      list("D_3_4_C_1_2"),
      list("E_", rep(1:2, 4), "_", rep(1:4, each=2))
    )
    
    unlist(lapply(args, function(x){do.call(paste0, x)}))