Currently I do the following:
x <- cbind(c(1, 2, 3), c(4, 5, 6))
x.merged <- matrix(t(x), ncol=1)
to create one column with values 1, 4, 2, 5, 3, 6, from the matrix x. But relying on t(x) seems a bit clunky. Is there a better way to do this? I’d like to avoid a for-loop or apply if there’s a simpler built-in function that handles this sort of thing.
EDIT: To be clearer, x is just given to me. The first line of code above was only meant to illustrate the values involved. It might have been better for me to write:
> x
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
Actually, if you make it a vector it doesn’t take more than :
Or, if you really have to avoid
t()then you could do :This works for an arbitrary number of columns, but includes an apply. If you don’t want to use that one, you’ll have to manually specify all the columns you want to paste behind eachother. But the t() solution is by far the fastest :
Remember that a matrix can be seen as a vector with dimensions added to it, and is always read columnwise. So you cannot really avoid the
t()in your solution. You could always just use it as a vector, eg :just works, as long as you remember that the matrix is read columnwise. So in your case you’ll need
In case you really need it as a matrix, then :