jeromyanglim / learning_r

assorted notes to self while learning R
1 stars 0 forks source link

how to extract each row of a matrix as a separate vector in R? #12

Closed jeromyanglim closed 12 years ago

jeromyanglim commented 12 years ago

Assume we have this matrix

x <- matrix(1:9, ncol=3, byrow=TRUE)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
jeromyanglim commented 12 years ago
split(x, row(x))

returns

$`1`
[1] 1 2 3

$`2`
[1] 4 5 6

$`3`
[1] 7 8 9

where row(x) indicates the row number of each cell and thus indicates how to split x.

Similarly, split(x, col(x)) could be used to extract each column of a matrix as a separate vector.