francoiskroll
francoiskroll

Reputation: 1108

How can I append all the columns of a matrix into one?

I would like to append all the columns of my matrix into one single column.

Mock example

# Sample data
testmat <- matrix (data = seq(1:3), nrow = 3, ncol = 3)

> testmat
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

I am expecting

     [,1]
[1,]    1 
[2,]    2 
[3,]    3
[4,]    1
[5,]    2
[6,]    3
[7,]    1
[8,]    2
[9,]    3

My first guess was something like:

onecol <- as.matrix (apply (X = testmat, MARGIN = 2, FUN = cat))

But it is not returning anything useful.

Any help?

Upvotes: 2

Views: 45

Answers (1)

akrun
akrun

Reputation: 887501

We don't need to use to apply here. A matrix is a vector with dim attributes, so if we call the matrix again on the original matrix and specify the ncol then it will change it to a matrix with 1 column

matrix(testmat, ncol=1) 

or we can change the dim of the original matrix ('testmat')

dim(testmat) <- c(9, 1)

Upvotes: 4

Related Questions