[英]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. 我想将data1
与result1
cbind
,将data2
与result2
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_rows
和bind_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_rows
和map_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或等效于cbind
和rbind
的cbind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.