根据嵌套顺序修改数据框列表 [英] rbinding a list of lists of dataframes based on nested order
问题描述
我有一个数据框, df
和一个函数进程
返回两个数据框的列表, a
和 b
。我使用dlply在id列上分割 df
,然后返回数据框列表的列表。以下是实际数据和方法的示例数据/代码:
I have a dataframe, df
and a function process
that returns a list of two dataframes, a
and b
. I use dlply to split up the df
on an id column, and then return a list of lists of dataframes. Here's sample data/code that approximates the actual data and methods:
df <- data.frame(id1=rep(c(1,2,3,4), each=2))
process <- function(df) {
a <- data.frame(d1=rnorm(1), d2=rnorm(1))
b <- data.frame(id1=df$id1, a=rnorm(nrow(df)), b=runif(nrow(df)))
list(a=a, b=b)
}
require(plyr)
output <- dlply(df, .(id1), process)
输出
是数据框列表的列表,嵌套列表将始终有两个数据框,名为 a
和 b
。在这种情况下,外部列表的长度为4。
output
is a list of lists of dataframes, the nested list will always have two dataframes, named a
and b
. In this case the outer list has a length 4.
我想要生成的是一个数据框,所有的 a
数据框,以及一个 id
列,表示它们各自的值(我相信这是列在$ code> split_labels 属性,请参见str(输出))。那么对于 b
数据框也是如此。
What I am looking to generate is a dataframe with all the a
dataframes, along with an id
column indicating their respective value (I believe this is left in the list as the split_labels
attribute, see str(output)). Then similarly for the b
dataframes.
到目前为止,我已经部分地使用了这个质询以提供以下代码:
So far I have in part used this question to come up with this code:
list <- unlist(output, recursive = FALSE)
list.a <- lapply(1:4, function(x) {
list[[(2*x)-1]]
})
all.a <- rbind.fill(list.a)
其中给出了最终的 a
数据框(同样对于 b
具有不同的下标到列表
),但是它没有我需要的id列,我确信必须有一个更直接或优雅的解决方案。理想的情况是使用 plyr
。
Which gives me the final a
dataframe (and likewise for b
with a different subscript into list
), however it doesn't have the id column I need and I'm pretty sure there's got to be a more straightforward or elegant solution. Ideally something clean using plyr
.
推荐答案
不是很干净,但你可以尝试这样的东西(假设相同的数据生成过程)。
Not very clean but you can try something like this (assuming the same data generation process).
list.aID <- lapply(1:4, function(x) {
cbind(list[[(2*x) - 1]], list[[2*x]][1, 1, drop = FALSE])
})
all.aID <- rbind.fill(list.aID)
all.aID
all.aID
d1 d2 id1
1 0.68103 -0.74023 1
2 -0.50684 1.23713 2
3 0.33795 -0.37277 3
4 0.37827 0.56892 4
这篇关于根据嵌套顺序修改数据框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!