我有数组列表,需要将其重新整理为数据帧。
示例输入:
> box
[[1]]
, , 1
[,1] [,2] [,3] [,4]
[1,] -88.44636 -84.29698 -84.29698 -88.44636
, , 2
[,1] [,2] [,3] [,4]
[1,] 32.28459 32.28459 41.7449 41.7449
[[2]]
NULL
[[3]]
, , 1
[,1] [,2] [,3] [,4]
[1,] 108.3619 108.4818 108.4818 108.3619
, , 2
[,1] [,2] [,3] [,4]
[1,] -6.537015 -6.537015 -6.439103 -6.439103
[[4]]
, , 1
[,1] [,2] [,3] [,4]
[1,] 108.5949 114.2009 114.2009 108.5949
, , 2
[,1] [,2] [,3] [,4]
[1,] -3.03971 -3.03971 2.08105 2.08105
输入结构:
> str(box)
List of 4
$ : num [1, 1:4, 1:2] -88.4 -84.3 -84.3 -88.4 32.3 ...
$ : NULL
$ : num [1, 1:4, 1:2] 108.36 108.48 108.48 108.36 -6.54 ...
$ : num [1, 1:4, 1:2] 108.59 114.2 114.2 108.59 -3.04 ...
期望的输出:
> bound
X1 X2 X3 X4 X5 X6 X7 X8
1 -88.44636 -84.29698 -84.29698 -88.44636 32.284593 32.284593 41.744901 41.744901
2 NA NA NA NA NA NA NA NA
3 108.36186 108.48179 108.48179 108.36186 -6.537015 -6.537015 -6.439103 -6.439103
4 108.59490 114.20087 114.20087 108.59490 -3.039710 -3.039710 2.081050 2.081050
我写代码。它工作并给了我想要的outpur,但执行速度很慢:(
bound = NULL
for ( i in 1:length(box) ) {
if ( !is.null(dim(box[i][[1]])) ) {
bound = rbind(bound, data.frame(matrix(as.vector(box[i][[1]][1,,]),nrow=1)))
} else
bound = rbind(bound,rep(NA,8))
if ( i == 1) {
colnames(bound) = paste("X",1:8,sep="")
}
}
有人可以给我更简单快速的解决方案来处理问题吗?来自this discussion,apply
家庭看起来合适。但我不知道该怎么做。
答案 0 :(得分:2)
通过lapply
循环(list
),我们用NA
替换NULL元素,连接(c
)非NULL元素,{{1}获得rbind
输出。
matrix
我们可以将其转换为m1 <- do.call(rbind,lapply(box, function(x) if(is.null(x)) NA else c(x)))
data.frame
as.data.frame(m1)