简体   繁体   中英

How to convert a list to a matrix?

In R i have an object k with type "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"

i would like to transform to a matrix p of character like eg

> 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() and as.matrix() don't seem to do the job. In fact, k is the result of a matrix() call applied tpo the result of a vapply()-call.

Or

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

Assuming this is k :

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

You could use storage mode storage.mode<- .

Using David's data, 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM