[R] flatten a matrix and unflatten it

Gabor Grothendieck ggrothendieck at myway.com
Tue Mar 22 00:23:24 CET 2005


Bill Simpson <William.Simpson <at> drdc-rddc.gc.ca> writes:

: 
: I want to flatten a matrix and unflatten it again. Please tell me how to 
: do it.
: 
: 1. given a matrix:
: x1 y1 z1
: x2 y2 z2
: ...
: xk yk zk
: convert it to a vector:
: x1, y1, z1, x2, y2, z2, ..., xk, yk, zk
: 
: 2. given a vector:
: x1, y1, z1, x2, y2, z2, ..., xk, yk, zk
: convert it to a matrix
: x1 y1 z1
: x2 y2 z2
: ...
: xk yk zk
: 
: It is known that the number of dimensions is 3.
: 

myvector <- c(t(mymatrix))  
mymatrix <- matrix(myvector, byrow = TRUE, nc=3)  

If column-wise is ok rather than row-wise as you show, then
omit t() in the first line and byrow = TRUE in the second.




More information about the R-help mailing list