Andres
Andres

Reputation: 291

Bind data frames recursively

I have to data frames, same number of columns but different number of rows. I want to bind the columns of one data frame to the columns of the other data frame, but one to all the others, i.e., the first row of one data frame to all the other rows of the second data frame, and so on.

I tried with a for loop, but of course, for a large number of rows, it takes a long time. As an example:

df1 <- data.frame(replicate(5,sample(0:1,5,rep=TRUE)))
df2 <- data.frame(replicate(5,sample(0:1,5,rep=TRUE)))

b1 <- data.frame()
for (i in 1:nrow(df1)) {
    for (k in 1:nrow(df2)) {
        b1 <- rbind(b1, cbind(df1[i,], df2[k,]))
    }
}

In this case, b1 is a data frame of 25 rows and 10 columns.

I tried with do.call, but I get a one-to-one mapping, i.e., a data frame of 5 rows in this case (first column to first column, second column to second column, and so on).

Any ideas on how to improve this?

Thanks!

Upvotes: 1

Views: 724

Answers (1)

Rentrop
Rentrop

Reputation: 21507

If i understand you correctly this is the same as:

ind_1 <- rep(seq_len(nrow(df1)), each = nrow(df2))
ind_2 <- rep(seq_len(nrow(df2)), nrow(df1))

cbind(df1[ind_1, ], df2[ind_2, ])

Upvotes: 1

Related Questions