How to append a vector as a column in R matrix?
17,003
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.
Author by
Vince Miller
Statistics grad student at Southern Methodist University using python and R for analysis.
Updated on June 04, 2022Comments
-
Vince Miller almost 2 years
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.
-
Vince Miller about 6 yearsMy matrix has hundreds of rows. How can I change c(1,2) to account for this?
-
drmariod about 6 yearsI updated my answer to answer your comment here as well.
-
drmariod about 6 yearsjust realised you were asking how to add in front... Updated my answer agin :-) And talking about the many rows, I guess you know how many rows and you have a vector fitting into your matrix... So just use this vector
-
Vince Miller about 6 years@jojo the question explicitly states that the matrix has many rows