Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从R中的并行结构列表中提取多个数据帧_R_List_Dataframe_Extract - Fatal编程技术网

从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