Reputation: 300
Suppose I have a matrix similar as the one show below in R.
[,1] [,2] [,3]
[1,] 2 4 3
[2,] 2 5 7
How can append a column to the front like below.
[,1] [,2] [,3] [,4]
[1,] 1 2 4 3
[2,] 1 1 5 7
Lastly, the matrix has many rows.
Upvotes: 3
Views: 22157
Reputation: 11762
use cbind
cbind(c(1,2), matrix(1:6, nrow=2))
So in case you work with bigger data, imagine your matrix is saved as m
and you have a vector my_vector
you want to add as a column in front of this matrix, the command would be
new_m <- cbind(my_vector, m)
Make sure the dimension of your vector fit the number of rows in your matrix.
In case you want to add rows instead of columns, the command is called rbind
and is used in exactly the same way.
Upvotes: 6