R:如何将列表的不同元素堆叠在一起

时间:2016-07-26 03:43:24

标签: r data-manipulation

我有一个包含300多个元素的列表(lgtdata3),每个列表如下所示:

lgtdat3[[1]]
 $y
 [1] 3 3 3 

 $X

  1 0 1.178470  7.643059 0.5680831
  0 1 1.220708 10.272480 0.7268355
  0 0 0.000000  0.000000 0.0000000

 $id
 123

我希望将总列表的每个子列表中的y,x和id组件堆叠到一个数据帧中。我理想的结果如下:

 y:
 3 3 3 4 6 ...

 x:
 1 0 1.178470  7.643059   0.5680831
 0 1 1.220708  10.27248   0.7268355
 0 0 0.000120  0.000000   0.0000000 
 1 1 1.175660  7.6435459  0.5685431
 0 1 1.228708  10.272480  0.7265355
 0 0 0.001400  0.0156000  0.0055000
 ....

 id
 123 124 ... 

我尝试了以下方法,但没有一种方法正常工作:

 mnl = Reduce(merge,lgtdata3)
 mnl = lapply(lgtdata3, function (x) '[',(c('y', 'X','hhid'))) 

2 个答案:

答案 0 :(得分:1)

我们可以使用transpose中的purrr,然后使用list遍历lapply元素来执行连接/ rbind。

library(purrr)
res <- lapply(transpose(lgtdat3), function(x) if(all(sapply(x, is.matrix))) 
                 do.call(rbind, x) else unlist(x))
res
#$y
#[1] 3 3 3 4 6 4

#$x
#           [,1]       [,2]       [,3]
#1 0 -0.545880758 -0.5836272  0.4445853
#0 1  0.536585304  0.8474600 -0.4664951
#0 0  0.419623149  0.2660220 -0.8483700
#1 0  0.002311942 -0.7622144 -0.4690607
#0 1 -1.316908124 -1.4290903 -0.3349868
#0 0  0.598269113  0.3322444  1.5362522

#$id
#[1] 123 124

注意:假设是&#39; x&#39;元素是matrices

数据

set.seed(24) 
lgtdat3 <- list(list(y = c(3, 3, 3), x = `row.names<-`(matrix(rnorm(9), 3, 
            3), c("1 0", "0 1", "0 0")), id = 123), 
               list(y = c(4, 6, 4), x= `row.names<-`(matrix(rnorm(9), 3, 
             3), c("1 0", "0 1", "0 0")), id = 124))

答案 1 :(得分:1)

以下是基础R解决方案,在akrun的数据中进行了演示:

setNames(nm=names(lgtdat3[[1L]]),lapply(seq_along(lgtdat3[[1L]]),function(i)
    do.call(if (is.null(dim(lgtdat3[[1L]][[i]]))) c else rbind,lapply(lgtdat3,`[[`,i))
));
## $y
## [1] 3 3 3 4 6 4
##
## $x
##             [,1]       [,2]       [,3]
## 1 0 -0.545880758 -0.5836272  0.4445853
## 0 1  0.536585304  0.8474600 -0.4664951
## 0 0  0.419623149  0.2660220 -0.8483700
## 1 0  0.002311942 -0.7622144 -0.4690607
## 0 1 -1.316908124 -1.4290903 -0.3349868
## 0 0  0.598269113  0.3322444  1.5362522
##
## $id
## [1] 123 124
##