Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

r - converting a matrix to a list

Suppose I have a matrix foo as follows:

foo <- cbind(c(1,2,3), c(15,16,17))

> foo
     [,1] [,2]
[1,]    1   15
[2,]    2   16
[3,]    3   17

I'd like to turn it into a list that looks like

[[1]]
[1]  1 15

[[2]]
[1]  2 16

[[3]]
[1]  3 17

You can do it as follows:

lapply(apply(foo, 1, function(x) list(c(x[1], x[2]))), function(y) unlist(y))

I'm interested in an alternative method that isn't as complicated. Note, if you just do apply(foo, 1, function(x) list(c(x[1], x[2]))), it returns a list within a list, which I'm hoping to avoid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a cleaner solution:

as.list(data.frame(t(foo)))

That takes advantage of the fact that a data frame is really just a list of equal length vectors (while a matrix is really a vector that is displayed with columns and rows...you can see this by calling foo[5], for instance).

You could also do this, although it isn't much of an improvement:

lapply(1:nrow(foo), function(i) foo[i,])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...