从R中的并行结构列表中提取多个数据帧
我对列表的有限了解让我陷入了麻烦。我有一个列表,其中包含每个级别上长度不同的多个数据帧,具有并行结构,如下所示:从R中的并行结构列表中提取多个数据帧,r,list,dataframe,extract,R,List,Dataframe,Extract,我对列表的有限了解让我陷入了麻烦。我有一个列表,其中包含每个级别上长度不同的多个数据帧,具有并行结构,如下所示: list.fun <- function(y) { x1 <- data.frame(x = rnorm(20, mean=y)) x2 <- data.frame(x = rnorm(10, mean=y)) return(list(x1=x1, x2=x2)) } ## make list foo <- lapply(1:3, list.f
list.fun <- function(y) {
x1 <- data.frame(x = rnorm(20, mean=y))
x2 <- data.frame(x = rnorm(10, mean=y))
return(list(x1=x1, x2=x2))
}
## make list
foo <- lapply(1:3, list.fun)
list.fun您可以使用[
操作符选择名为x1
的所有元素:
lapply(foo, "[[", "x1")
然后,您可以使用do.call
do.call(rbind, lapply(foo, '[[', "x1"))
> head(do.call(rbind, lapply(foo, '[[', "x1")))
x
1 1.3599227
2 0.7760733
3 0.9852219
4 0.5447365
5 2.1185779
6 0.5419102
> nrow(do.call(rbind, lapply(foo, '[[', "x1")))
[1] 60
对于更一般的情况:
res <- do.call(rbind, lapply(seq_along(foo)
, function(x){
out <- foo[[x]][['x1']]
out$trial <- paste0("t", x)
out
}
)
)
> head(res)
x trial
1 1.3599227 t1
2 0.7760733 t1
3 0.9852219 t1
4 0.5447365 t1
5 2.1185779 t1
6 0.5419102 t1
res
res <- do.call(rbind, lapply(seq_along(foo)
, function(x){
out <- foo[[x]][['x1']]
out$trial <- paste0("t", x)
out
}
)
)
> head(res)
x trial
1 1.3599227 t1
2 0.7760733 t1
3 0.9852219 t1
4 0.5447365 t1
5 2.1185779 t1
6 0.5419102 t1