Convert a matrix to a 1 dimensional array Convert a matrix to a 1 dimensional array arrays arrays

Convert a matrix to a 1 dimensional array


Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.

> m=matrix(1:12,3,4)> m     [,1] [,2] [,3] [,4][1,]    1    4    7   10[2,]    2    5    8   11[3,]    3    6    9   12> as.vector(m) [1]  1  2  3  4  5  6  7  8  9 10 11 12> as.vector(t(m)) [1]  1  4  7 10  2  5  8 11  3  6  9 12


try c()

x = matrix(1:9, ncol = 3)x     [,1] [,2] [,3][1,]    1    4    7[2,]    2    5    8[3,]    3    6    9c(x)[1] 1 2 3 4 5 6 7 8 9


If we're talking about data.frame, then you should ask yourself are the variables of the same type? If that's the case, you can use rapply, or unlist, since data.frames are lists, deep down in their souls...

 data(mtcars) unlist(mtcars) rapply(mtcars, c) # completely stupid and pointless, and slower