0

I want to create a function where the merging of two data frames occurs in pairs (i.e. df1 column 1 is next to df2 column 1, and then df1 column 2 is next to df2 column 2 (etc.)). Below is a script to make a two random data frames for reproducibility.

    df1 <- data.frame(replicate(10,rnorm(20)))
    df2 <- data.frame(replicate(10,rnorm(20)))

Essentially the goal outcome would be to have df1$X1 be next to df2$X1 , and then df1$X2 be next to df2$X2 and so on, stored in a new data frame (e.g. df3). I know it is possible to write it out in a data.frame() command but that would take too long. Is there a function which achieves this?

I know this question will likely have already been answered but I am unsure how to word the question and have as such not been able to find any way of doing this. Any help would be much appreciated. Thank you so much!

Luuk
  • 75
  • 5

1 Answers1

1

One possibility is to use Map

do.call(cbind, Map(cbind, df1, df2))

or mapply

do.call(cbind, mapply(cbind, df1, df2, SIMPLIFY = F))

Explanation: The inner cbind binds columns pairwise from df1 and df2. The outer cbind binds the list of paired columns into the final data.frame.


Using a pair of smaller sample data.frames with a fixed seed (for reproducibility), here is an example:

set.seed(2017);
df1 <- data.frame(replicate(2, rnorm(4)))
df2 <- data.frame(replicate(2, rnorm(4)))

do.call(cbind, Map(cbind, df1, df2))
#            [,1]       [,2]         [,3]       [,4]
#[1,]  1.43420148 -0.2653360 -0.069825227 -0.7467347
#[2,] -0.07729196  1.5632226  0.451905527  0.3066498
#[3,]  0.73913723  0.3427681 -1.958366456 -1.4304858
#[4,] -1.75860473  1.5724254 -0.001524259  1.1944265
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68