2

I have 2 lists of dataframes. Each list has 24 dataframes

list1 <- (data1, data2, ..., data24)
list2 <- (result1, result2, ...., result3)

I want to cbind data1 with result1, data2 with result2 and so on. Then rbind all dataframes together like that:

all1 <- cbind(data1, result1)
all2 <- cbind(data2, result2)
all.in <- rbind(all1, all2)

How to do that efficiently with 24 dataframes?

alistaire
  • 42,459
  • 4
  • 77
  • 117
Thuong Tra
  • 19
  • 3

2 Answers2

7

In tidyverse grammar, dplyr::bind_rows and bind_cols will bind a list together, and are invoked by purrr::map_df variants:

library(tidyverse)

l1 <- list(mtcars[1:2, 1, drop = FALSE], mtcars[3:4, 1, drop = FALSE])
l2 <- list(mtcars[1:2, 2:6], mtcars[3:4, 2:6])

map2_dfr(l1, l2, bind_cols)
#>    mpg cyl disp  hp drat    wt
#> 1 21.0   6  160 110 3.90 2.620
#> 2 21.0   6  160 110 3.90 2.875
#> 3 22.8   4  108  93 3.85 2.320
#> 4 21.4   6  258 110 3.08 3.215

An .id parameter can be passed to both bind_rows and map_dfr, and will result in a new column with the name supplied consisting of an index for which list element each observation came from.

alistaire
  • 42,459
  • 4
  • 77
  • 117
5

I would probably do something like this:

l1 <- list(mtcars,mtcars)
l2 <- list(mtcars,mtcars)
do.call(rbind,mapply(FUN = cbind,l1,l2,SIMPLIFY = FALSE))

If the data frames are very large, you might switch to the dplyr or data.table equivalents of cbind and rbind.

joran
  • 169,992
  • 32
  • 429
  • 468