3

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.

1 Answers1

2

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.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thats right! But can you explaind why this solution works? What do these numbers in the bracket mean? How did you get that solution? –  Oct 08 '14 at 16:06
  • @Trik23 I updated with some explanation. Also, here is a link to R-intro http://cran.r-project.org/doc/manuals/R-intro.html – akrun Oct 08 '14 at 16:17
  • @Trik23 No problem. The indexing is very helpful in a lot of situations and you can avoid unnecessary `loops`. – akrun Oct 08 '14 at 16:24
  • @Trik23 Here is a link http://stackoverflow.com/questions/1744861/how-to-learn-r-as-a-programming-language that gives suggestions about books and other links as well. You can also check the `coursera.org` https://www.coursera.org/course/rprog – akrun Oct 08 '14 at 17:22