Dear List, I want to turn the matrix> xm[,1] [,2] [1,] "a" "b" [2,] "d" "e" into a list "by rows" as: [[1]] [1] "a" "b" [[2]] [1] "d" "e" A (bad?) way of doing this is as> unlist(apply(xm,1, list), recursive=F)[[1]] [1] "a" "b" [[2]] [1] "d" "e" - but there must be a more elegant way. Can anyone help on this? Thanks! S?ren
Try split:> x <- matrix(letters[1:4], 2) > x[,1] [,2] [1,] "a" "c" [2,] "b" "d"> split(x, row(x))$`1` [1] "a" "c" $`2` [1] "b" "d" -Christos> -----Original Message----- > From: r-help-bounces at r-project.org > [mailto:r-help-bounces at r-project.org] On Behalf Of S?ren H?jsgaard > Sent: Monday, November 12, 2007 8:08 PM > To: r-help at stat.math.ethz.ch > Subject: [R] The "reverse" of do.call("rbind",) on a list > > Dear List, > I want to turn the matrix > > xm > [,1] [,2] > [1,] "a" "b" > [2,] "d" "e" > > into a list "by rows" as: > [[1]] > [1] "a" "b" > [[2]] > [1] "d" "e" > > A (bad?) way of doing this is as > > unlist(apply(xm,1, list), recursive=F) > [[1]] > [1] "a" "b" > [[2]] > [1] "d" "e" > > - but there must be a more elegant way. Can anyone help on > this? Thanks! > S?ren > > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > >
Try: split(xm, row(xm)) On Nov 12, 2007 8:07 PM, S?ren H?jsgaard <Soren.Hojsgaard at agrsci.dk> wrote:> Dear List, > I want to turn the matrix > > xm > [,1] [,2] > [1,] "a" "b" > [2,] "d" "e" > > into a list "by rows" as: > [[1]] > [1] "a" "b" > [[2]] > [1] "d" "e" > > A (bad?) way of doing this is as > > unlist(apply(xm,1, list), recursive=F) > [[1]] > [1] "a" "b" > [[2]] > [1] "d" "e" > > - but there must be a more elegant way. Can anyone help on this? Thanks! > S?ren > > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
On Tue, 13 Nov 2007 02:07:39 +0100, S?ren H?jsgaard <Soren.Hojsgaard at agrsci.dk> wrote:> Dear List, I want to turn the matrix >> xm > [,1] [,2] [1,] "a" "b" [2,] "d" "e"> into a list "by rows" as: [[1]] [1] "a" "b" [[2]] [1] "d" "e"> A (bad?) way of doing this is as >> unlist(apply(xm,1, list), recursive=F) > [[1]] [1] "a" "b" [[2]] [1] "d" "e"> - but there must be a more elegant way. Can anyone help on this?How about: lapply(seq(nrow(xm)), function(k) xm[k, ]) ? -- Seb