Alexander Hempfing
Alexander Hempfing

Reputation: 247

Replacing matrix columns in R

I created a matrix in R

C<-matrix(c(0),nrow=6,ncol=6,byrow = FALSE)

Now I would like to replace the first column of the matrix with the value 1, the second and third column with standard normal random variables and the last three columns with the values of an other matrix.

Upvotes: 2

Views: 13487

Answers (2)

akash87
akash87

Reputation: 3994

For the first three columns, you can use

C<-matrix(c(0),nrow=6,ncol=6,byrow = FALSE)
C[ ,1] <- 1; C[ ,2] <- rnorm(6); C[ ,3] <- rnorm(6)

Let's now say your other matrix is called D and looks like

          [,1]       [,2]       [,3]      [,4]      [,5]      [,6]      [,7]
[1,] 0.6527716 0.81793644 0.67138209 0.3175264 0.1067119 0.5907180 0.4619992
[2,] 0.2268516 0.90893913 0.62917211 0.1768426 0.3659889 0.0339911 0.2322981
[3,] 0.9264116 0.81693835 0.59555163 0.6960895 0.1667125 0.6631861 0.9718530
[4,] 0.2613363 0.06515864 0.04971742 0.7277188 0.2580444 0.3718222 0.8028141
[5,] 0.2526979 0.49294947 0.97502566 0.7962410 0.8321882 0.2981480 0.7098733
[6,] 0.4245959 0.95951112 0.45632856 0.8227812 0.3542232 0.2680804 0.7042317

Now let's say you want columns 3,4, and 5 in from D as the last three columns in C, then you can simply just say

C[ ,4:6] <- D[ ,3:5]

And your result is

     [,1]        [,2]       [,3]       [,4]      [,5]      [,6]
[1,]    1 -1.76111875  0.4621061 0.67138209 0.3175264 0.1067119
[2,]    1  0.40036245  0.9054436 0.62917211 0.1768426 0.3659889
[3,]    1 -1.03238266 -0.6705829 0.59555163 0.6960895 0.1667125
[4,]    1 -0.47064774  0.3119684 0.04971742 0.7277188 0.2580444
[5,]    1 -0.01436411 -0.4688032 0.97502566 0.7962410 0.8321882
[6,]    1 -1.18711832  0.8227810 0.45632856 0.8227812 0.3542232

Just one thing to note is that this requires your number of rows to be the same between C and D.

Upvotes: 0

Bryan Goggin
Bryan Goggin

Reputation: 2489

C<-matrix(c(0),nrow=6,ncol=6,byrow = FALSE)
other.matrix<-matrix(runif(18), nrow = 6, ncol = 3)

C[,1]<-1
C[,3]<-rnorm(6)
C[,4:6]<-other.matrix

To access the rows and columns of matrices (and for that matter, data.frames) in R you can use [] brackets and i,j notation, where i is the row and j is the column. For example, the 3rd row and 2nd column of your matrix C can be addressed with

 C[3,2]
 #[1] 0

Use <- to assign new values to the rows/columns you have selected.

Upvotes: 2

Related Questions