Home > Enterprise >  Replace a partition of a column of a matrix with a vector
Replace a partition of a column of a matrix with a vector

Time:12-31

I have 2 matrices/dataframes, A and B, with dimensions 50x30 each.

How can I replace the first 11 elements of each column of matrix A with the 11 elements of each column, respectively, of matrix B, without having do loop each column?

Example (for matrices 3x3 and n_replace = 2):

matrix A      matrix B         resultant matrix
v1 v2 v3     v1 v2 v3          v1 v2 v3
1  2  1      12 99 .31   ->    12 99 .31    # replaced from matrix B
5  4  1      33 .2 12          33 .2 12     # replaced from matrix B
9  2  3      10 .3 14          9  2  3      # remained from matrix A

I think I can do something like

for(i in 1:3) {
   replace(A[,i], c(1:n_replace), B[1:n_replace,i])
}

But is there a more straight forward/smart way to do this in R?

CodePudding user response:

From your example, you can do:

A[1:2,] <- B[1:2,]
A
#     [,1] [,2]  [,3]
#[1,]   12 99.0  0.31
#[2,]   33  0.2 12.00
#[3,]    9  2.0  3.00

The logic is the same if you want to replace the values for the first 11 elements of each column:

A[1:11,] <- B[1:11,]

Data

A = matrix(c(1,5,9,2,4,2,1,1,3),nrow=3)
B = matrix(c(12,33,10,99,.2,.3,.31,12,14),nrow=3)

CodePudding user response:

Try this:

df_result <- df[1:11,]<- df1[1:11,]
  • Related