mandy
mandy

Reputation: 503

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!!

Upvotes: 1

Views: 250

Answers (2)

Darren Tsai
Darren Tsai

Reputation: 35554

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)

Upvotes: 1

Douglas Mesquita
Douglas Mesquita

Reputation: 1021

You can use expand.grid:

expand.grid(A = df1, B = df2)
  A B
1 1 4
2 2 4
3 3 4
4 1 5
5 2 5
6 3 5
7 1 6
8 2 6
9 3 6

Upvotes: 4

Related Questions