user4110499
user4110499

Reputation:

Change a part of a bigger matrix with a smaller one

I have two matrices and I would like to change a part of the bigger one with the smaller one.

So this is the first and this is the second matrix:

Bigger matrix:

matrix1=matrix(1:36,nrow=6,ncol=6)

Smaller matrix:

matrix2=matrix(1:10,nrow=2,ncol=5)

And by merging them the result should be somethink like this:

       [,1] [,2][,3] [,4]  [,5][,6]
[1,]    1    7   13   19   25   31
[2,]    2    8   14   20   26   32
[3,]    3    9   15   21   27   33
[4,]    1   3    5    7    9    34
[5,]    2   4    6    8    10   35
[6,]    6   12   18   24   30   36

where just a part of the result matrix has the smaller one inside the bigger one at a specific part.

Upvotes: 3

Views: 596

Answers (1)

akrun
akrun

Reputation: 887048

Here, the rules are not clear. It seems like you want to replace 4th and 5th row of matrix1 from columns 1 to 5 with matrix2. In that case:

 matrixNew <- matrix1  #created a copy of `matrix1`
 matrixNew[4:5,-6] <- matrix2 #replace values in `matrixNew on rows 4 and 5 from columns 1 to 5 with matrix2 values
 matrixNew
 #       [,1] [,2] [,3] [,4] [,5] [,6]
 #[1,]    1    7   13   19   25   31
 #[2,]    2    8   14   20   26   32
 #[3,]    3    9   15   21   27   33
 #[4,]    1    3    5    7    9   34
 #[5,]    2    4    6    8   10   35
 #[6,]    6   12   18   24   30   36

The specific part where the smaller one sits inside the bigger one is on rows 4 and 5 and on columns 1 to 5. So, I used the [ to subset with rowindex 4:5 i.e. 4 and 5, and column index -6. In matrix1, there are 6 columns, so, -6 removes the 6th column and leave 1:5 columns in the subset. The values based on the index are replaced by matrix2 values.

Upvotes: 2

Related Questions