合并列表中的列表

时间:2012-07-30 18:13:03

标签: r

我有一个像

这样的清单
$`1`
[1] 1959   13

$`2`
[1] 2280  178   13

$`3`
[1] 2612  178   13

$`4`
[1] 2902  178   13

结构类似于:

structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612, 
178, 13), `4` = c(2902, 178, 13)......,.Names = c("1", "2", "3", "4"....)

如何组合此列表中的列表并生成如下列表:

$`list`
[1] 1959   13
[2] 2280  178   13
[3] 2612  178   13
[4] 2902  178   13

2 个答案:

答案 0 :(得分:4)

这是我能得到的最接近你要求的矩阵:

LIST <- structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612, 
178, 13), `4` = c(2902, 178, 13)))

cbind.fill <-
function(...) {
    nm <- list(...)
    nm<-lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow))
    do.call(cbind, lapply(nm, function(x) rbind(x, 
        matrix(, n - nrow(x), ncol(x)))))
}

t(do.call('cbind.fill', LIST))
print(X$list, na.print="", quote=FALSE)

或使用plyr

LIST <- lapply(LIST, function(x) data.frame(t(x)))
library(plyr)
rbind.fill(LIST)

也许你只是不想要名字?

如果是这样......

names(LIST) <- NULL
LIST

我想我只是没有得到你想要的输出结构。

答案 1 :(得分:0)

尝试以下代码。问题是我不太确定你想要什么作为你的输出;你把它称为列表,但它看起来很像矩阵。假设您确实希望它作为矩阵,以下应该可以解决这个问题:

x <- list()
x$`1` <- c(1959, 13)
x$`2` <- c(2280, 178, 13)
x$`3` <- c(2612, 178, 13)
x$`4` <- c(2902, 178, 13)

# maximum number of elements in any vector
max <- max(sapply(x, function(y) length(y)))

# make all vectors the same length
x <- lapply(x, function (y){length(y) <- max; y})

# combine them in a matrix
result <- do.call(rbind, x)

结果:

> result
  [,1] [,2] [,3]
1 1959   13   NA
2 2280  178   13
3 2612  178   13
4 2902  178   13

您始终可以将此矩阵输出另存为列表元素。我的想法是让长度等于here

如果您希望矩阵为数字(您可以随时将其转换为字符并使NA为“”,那么您将无法摆脱NA,但对于进一步的工作可能不是一个好主意矩阵)。

可能是我很困惑,毕竟你想要一个清单,但正如Josh在评论中提到的那样,你的数据在这种情况下是正确的。