如何将列表转换为矩阵?

时间:2014-09-22 10:54:37

标签: r

在R中我有一个对象k,其类型为" list":

> k
     [,1] [,2] [,3] [,4]
[1,] "aa" "cg" "cg" "tt"
[2,] "ag" "gg" "gt" "tt"
> dim(k)
[1] 2 4
> typeof(k)
[1] "list"

我想转换为字符矩阵p,例如

> p
     [,1] [,2] [,3] [,4]
[1,] "aa" "cg" "gc" "tt"
[2,] "ag" "gg" "gt" "tt"
> dim(p)
[1] 2 4
> typeof(p)
[1] "character"

matrix()和as.matrix()似乎没有完成这项工作。实际上,k是应用了一个矩阵()调用的结果tpo(vapply() - 调用的结果。

2 个答案:

答案 0 :(得分:2)

p <- as.character(k)
dim(p) <- dim(k)
typeof(p)
## [1] "character"
dim(p)
## [1] 2 4

假设这是k

k <- structure(list("aa", "cg", "cg", "tt", "ag", "gg", "gt", "tt"),
               .Dim = c(2L, 4L))

答案 1 :(得分:1)

您可以使用存储模式storage.mode<-

使用David的数据k

k <- structure(list("aa", "cg", "cg", "tt", "ag", "gg", "gt", "tt"),
               .Dim = c(2L, 4L))
typeof(k)
# [1] "list"
storage.mode(k) <- "character"
typeof(k)
# [1] "character"
dim(k)
# [1] 2 4
is.matrix(k)
# [1] TRUE
dput(k)
# structure(c("aa", "cg", "cg", "tt", "ag", "gg", "gt", "tt"), .Dim = c(2L, 
# 4L))