我需要用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
我该如何解决? 感谢
答案 0 :(得分:2)
首先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
答案 1 :(得分:0)
我们可以使用包装函数simplify2array
`colnames<-`(simplify2array(x), c("N", "perS", "perM"))
# N perS perM
#[1,] 10 12 0
#[2,] 10 11 0