R Modifying a region of a matrix/data frame depending on another matrix/data frame
I have a question about modifying a matrix. I have managed to change values in a matrix depending on the value of another matrix when they are of the same dimension. But now I need to apply this procedure to matrixes with different dimensions. In other words, I want to apply some changes to a "region" of the bigger matrix depending on the values of the smaller one, bearing in mind that I know the positions of the smaller matrix associated to the bigger one.
Suppose this are matrix A
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
and B
0 0 0 0 0 0
0 1 1 1 1 0
0 0 1 1 1 0
0 0 1 1 0 0
0 0 0 0 0 0
I know that B[1,1] is the value I have to check to modify A[2,1], B[2,1] for A[3,1] and so on...
The final result I am looking for is
1 2 3 4 5 6 7 8
1 2 0 0 0 0 7 8
1 2 3 0 0 0 7 8
1 2 3 0 0 6 开发者_StackOverflow中文版7 8
1 2 3 4 5 6 7 8
For the A values replacement I use a for loop in my original script
for (i in 1:10) A[B == i] = 0
that works when A and B have same dimension.
How should I make the replacement in matrix A? apply? a for loop?
Any help would be appreciated and of course you can point me to some basic reading I haven't still read.
Just select the submatrix and do what you want, i.e.:
A[1:5,2:8][B == 1] = 0
Or, in general, if [row, col] is the starting position of matrix B in matrix A:
A[row:nrow(A),col:ncol(A)][B == 1] = 0
Here is the test code so that you can check it works:
A = matrix(rep(1:8, each = 5), nrow = 5)
B = matrix(c(rep(0, 7), 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, rep(0, 8)), nrow = 5, byrow = TRUE)
A[1:5,2:8][B == 1] = 0
Thanks to Andrie ho for hinting me the ncol
function instead of ugly dim(A)[2]...
精彩评论