go from
m <- matrix(1:16, nrow = 4)
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
to
1x16 matrix 1 5 2 6 3 7 4 8 9 13 10 14 11 15 12 16
tried to flatten this but didn't work
> flattened_matrix <- matrix(m, nrow = 1, byrow = TRUE)
> flattened_vector <- as.vector(t(flattened_matrix))
Update:
Okay so the order you are wanting is quite strange. I'm unsure what the underlying rules are, but I'm assuming here you are wanting to grab the values in the first two columns, then the next set of two columns, etc.
Original:
The heart of this problem is with the function
matrix()'s argumentbyrow. From the documentation:Note that with a one row or one column matrix, filling by row or by column is the same thing. The byrow argument decides how we fill the output matrix, not the order in which we take elements from the input matrix.
To get this working, you could do many things. One option is transposing the matrix
mfirst, and another is creating a new 4x4 matrix withbyrow = TRUEthen turning that into a one row matrix or a vector:Output(s):