从列表中填充矩阵
问题描述:
我需要用coloumn填充矩阵。从列表中填充矩阵
我有这样的名单:
> print(list_all)
[[1]]
[[1]][[1]]
[1] 10
[[1]][[2]]
[1] 10
[[2]]
[[2]][[1]]
[1] 12
[[2]][[2]]
[1] 11
[[3]]
[[3]][[1]]
[1] 0
[[3]][[2]]
[1] 0
我想创建这样一个矩阵:
N perS perM
10 12 0
10 11 0
这是我做了什么:
mat <- matrix(list_all[],
byrow = FALSE,
ncol = 3,
nrow = permutations*length(listN))
colnames(mat) <- list ("N", "perS", "perM")
print(mat)
,其结果是:
N perS perM
[1,] List,4 List,4 List,4
[2,] List,4 List,4 List,4
我该如何解决? 谢谢
答
只是unlist()
它第一次。您也可以使用dimnames
同时设置名称。
## example list
x <- list(list(10, 10), list(12, 11), list(0, 0))
matrix(
unlist(x),
unique(lengths(x)),
dimnames = list(NULL, c("N", "perS", "perM"))
)
# N perS perM
# [1,] 10 12 0
# [2,] 10 11 0
你也可以用sapply()
来做,但上面的方法会更快。
`colnames<-`(sapply(x, unlist), c("N", "perS", "perM"))
# N perS perM
# [1,] 10 12 0
# [2,] 10 11 0
答
我们可以用一个包装函数simplify2array
`colnames<-`(simplify2array(x), c("N", "perS", "perM"))
# N perS perM
#[1,] 10 12 0
#[2,] 10 11 0
这就是我要去的解决方案,并即将发布。 :)但是,它确实需要您指定尺寸。 – Gopala
@ HaddE.Nuff谢谢,它完美的工作:-) – marielle