Search code examples
rcbind

cbind each row from one data to another in R


My dataset looks like this:

df1<-t(data.frame(1,2,3))
df2<-t(data.frame(4,5,6))
colnames(df1)<-c('A')
colnames(df2)<-c('B')
> df1
   A
X1 1
X2 2
X3 3
> df2
   B
X4 4
X5 5
X6 6

How can I merge each row in df1 to df2 so that I have something like this:

A  B  
1  4
1  5
1  6
2  4
2  5
2  6
3  4
3  5
3  6

Thanks!!


Solution

  • This question is likely to be a duplicate. Here are three similar solutions:

    • merge(df1, df2)
    • expand.grid(A = df1, B = df2)
    • tidyr::crossing(A = df1, B = df2)