2017-01-11 108 views
2

我已經看過各種綁定列表問題,如this,但我無法真正找到一個更有效的方法來做到這一點。rbind嵌套列表中的數據幀

我有一個包含三個列表,每個包含兩個dataframes嵌套列表nestlist

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列rbind從列表1,列表2和表3的每個對象讓我結束了:

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 

回答

3

您可以使用do.call(Map, ...),這傳遞嵌套列表作爲參數傳遞給該地圖將通過這些列表循環以並行的方式,並呼籲rbind作爲Map功能將在相同的位置結合在一起名單:

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 
+0

我真的很喜歡這個解決方案 - 簡單,高效 - 謝謝!我想知道它是否比@akrun解決方案更快 – Bonono

1

我們可以嘗試

library(purrr) 
lapply(transpose(nestedlist), function(x) do.call(rbind, x)) 

或者使用bind_rowsdplyr

library(dplyr) 
transpose(nestedlist) %>% 
       map(bind_rows) 
#[[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