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. Thanks for any help! Bill
If you can rearrange things to work column-wise rather than row-wise, then dim(x) <- NULL makes a matrix into a vector by concatenating columns, and dim(x) <- c(m,n) makes the vector x into a matrix with column 1 equal to the first m elements of x, column 2 equal to the next m elements, etc. If you need row-major order, you can do x <- as.vector(t(x)) and x <- matrix(x,nrow=m,ncol=n,byrow=TRUE) Reid Huntsinger -----Original Message----- From: r-help-bounces at stat.math.ethz.ch [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Bill Simpson Sent: Monday, March 21, 2005 4:44 PM To: r-help Subject: [R] flatten a matrix and unflatten it 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. Thanks for any help! Bill ______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
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.
Sorry -- I meant to say "dataframe" instead of matrix. Anyway I see that my troubles are gone when I scan the data in as a vector then convert to matrix. (I had troubles doing such manipulations when I read in the data using read.table) x<-scan("/home/wsimpson/papers/face/max.dat") xx<-matrix(x, ncol=3, nrow=length(x)/3, byrow=T) Thanks for the help. Bill