简体   繁体   English

如何绑定和绑定2个数据帧列表

[英]How to cbind and rbind 2 lists of dataframes

I have 2 lists of dataframes. 我有2个数据框列表。 Each list has 24 dataframes 每个列表都有24个数据框

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

I want to cbind data1 with result1 , data2 with result2 and so on. 我想将data1result1 cbind ,将data2result2 cbind ,依此类推。 Then rbin d all dataframes together like that: 然后像这样将所有数据帧rbin在一起:

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

How to do that efficiently with 24 dataframes? 如何使用24个数据帧有效地做到这一点?

In tidyverse grammar, dplyr::bind_rows and bind_cols will bind a list together, and are invoked by purrr::map_df variants: 在tidyverse语法中, dplyr::bind_rowsbind_cols将一个列表绑定在一起,并由purrr::map_df变体调用:

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. 可以将.id参数传递给bind_rowsmap_dfr ,并将产生一个新列,其名称由提供的索引组成,该索引包含每个观察值所来自的列表元素。

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 . 如果数据帧很大,则可以切换到dplyr或等效于cbindrbindcbind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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