Paste all combinations of two separate vectors in R

1k Views Asked by At

I have two vectors

df1 <- c("a","b","c")
df2 <- c("1","2","3")

 # expected output
 #  a1 a2 a3 b1 b2 b3 c1 c2 c3

I've seen Paste all combinations of a vector in R, However, That doesn't solve my dilemma.

3

There are 3 best solutions below

1
On BEST ANSWER

Another approach:

df1 <- c("a","b","c")
df2 <- c("1","2","3")

apply(expand.grid(df1, df2), 1, paste, collapse="")
0
On

Like this:

paste0(rep(df1, length(df1)), rep(df2, length(df2)))

Or this:

df_comb <- expand.grid(df1, df2)
paste0(df_comb$Var1, df_comb$Var2)
0
On

You can merge: apply(merge(df1, df2), 1, function(row) paste(row[1], row[2], sep = ''))