converting a matrix to a list

前端 未结 2 1917
醉酒成梦
醉酒成梦 2020-12-05 08:34

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          


        
相关标签:
2条回答
  • 2020-12-05 09:15

    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,])
    
    0 讨论(0)
  • 2020-12-05 09:36
    library(plyr)
    alply(foo, 1)
    
    0 讨论(0)
提交回复
热议问题