简体   繁体   中英

How to cbind and rbind 2 lists of dataframes

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 rbin d 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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM