嵌套列表中的rbind数据框 [英] rbind dataframes across nested lists

查看:57
本文介绍了嵌套列表中的rbind数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过各种绑定列表问题,例如 this ,但我真的找不到更有效的方法.

I've had a look at various rbinding list questions such as this but I can't really find a more efficient way of doing this.

我有一个嵌套列表 nestlist ,其中包含三个列表,每个列表包含两个数据帧:

I have a nested list nestlist that contains three lists which each contain two dataframes:

df1 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples")
df2 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueB = seq(0.1,0.4,0.1),  Category= "Apples")
list1 <- list(df1,df2)

df3 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueA = seq(0.1,0.4,0.1), Category= "Pears")
df4 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueB = seq(0.1,0.4,0.1),  Category= "Pears")
list2 <- list(df3,df4)

df5 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueA = seq(0.1,0.4,0.1), Category= "Stairs")
df6 <- data.frame(ID = paste0(LETTERS[1:4],1:4), valueB = seq(0.1,0.4,0.1),  Category= "Stairs")
list3 <- list(df5,df6)

nestedlist <- list(list1,list2,list3)

我想找到一种更简单的方法,可以通过常见的 value 列来对list1,list2和list 3中的每个对象进行绑定,以便最终得到:

I want to find an easier way to rbind each object from list1, list2 and list 3 by the common value column so that I end up with:

rbind(nestedlist[[1]][[1]],nestedlist[[2]][[1]], nestedlist[[3]][[1]])

  ID   A Category
1  A1 0.1   Apples
2  B2 0.2   Apples
3  C3 0.3   Apples
4  D4 0.4   Apples
5  A1 0.1    Pears
6  B2 0.2    Pears
7  C3 0.3    Pears
8  D4 0.4    Pears
9  A1 0.1   Stairs
10 B2 0.2   Stairs
11 C3 0.3   Stairs
12 D4 0.4   Stairs

推荐答案

您可以使用 do.call(Map,...),这会将嵌套列表作为参数传递给Map,它将循环循环并行浏览这些列表并调用 rbind ,因为 Map 函数会将列表中相同位置的列表绑定在一起:

You can use do.call(Map, ...), this passes the nested lists as arguments to Map which will loop through these lists in a parallel way and call rbind as the Map function will bind lists at the same positions together:

do.call(Map, c(f = rbind, nestedlist))

# [[1]]
#    ID valueA Category
# 1  A1    0.1   Apples
# 2  B2    0.2   Apples
# 3  C3    0.3   Apples
# 4  D4    0.4   Apples
# 5  A1    0.1    Pears
# 6  B2    0.2    Pears
# 7  C3    0.3    Pears
# 8  D4    0.4    Pears
# 9  A1    0.1   Stairs
# 10 B2    0.2   Stairs
# 11 C3    0.3   Stairs
# 12 D4    0.4   Stairs
# 
# [[2]]
#    ID valueB Category
# 1  A1    0.1   Apples
# 2  B2    0.2   Apples
# 3  C3    0.3   Apples
# 4  D4    0.4   Apples
# 5  A1    0.1    Pears
# 6  B2    0.2    Pears
# 7  C3    0.3    Pears
# 8  D4    0.4    Pears
# 9  A1    0.1   Stairs
# 10 B2    0.2   Stairs
# 11 C3    0.3   Stairs
# 12 D4    0.4   Stairs

这篇关于嵌套列表中的rbind数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆