简体   繁体   中英

How to append a vector as a column in R matrix?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM