user1479670
user1479670

Reputation: 1301

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 e.g.

> 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.

Upvotes: 1

Views: 122

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99391

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))

Upvotes: 1

David Arenburg
David Arenburg

Reputation: 92310

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))

Upvotes: 2

Related Questions