Reputation: 35
I have a matrix with ID values at grid points and I have a vector containing some of those ID's. I would like to write a function so that for all the ID's contained in the vector, the corresponding ID in the matrix is set to 0.
For example:
ID <- matrix(c(2,3), nrow=2)
A <- matrix(c(0, 0, 2, 2, 0, 3,
1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 4,
1, 0, 1, 0, 0, 4), nrow=4, byrow=TRUE)
I would like to transform my matrix A so that the 2's and 3 become 0.
I found a way to do this manually with the "if" function, setting conditions:
a <- nrow(A)
b <- ncol(A)
vide <- array(NaN, dim=c(a,b))
for (i in c(1:a)) {for (j in c(1:b)) {
if ( (A[i,j]==ID[1,1]) | (A[i,j]==ID[2,1]) ) {
vide[i,j]==0} else {vide[i,j]=A[i,j]}
}
}
vide[is.na(vide)] <- 0
But I would like to create an automatic function that will do this for all the ID's contained in the ID vector, regardless of the number of rows. Because I will then run this over many years and the ID matrix will not always have the same number of rows. Is there a way to do that ?
I also tried another way, to make R write the conditions in the "if" function by itself:
d <- nrow(ID)
Cond <- array(NaN, dim=c(d,1))
for (k in c(1:d)) {
Cond[k,1]=paste("(A[i,j]==ID[",k,",1]) ", sep="")
}
Cond <- t(Cond)
Cond <- paste(Cond,collapse="| ")
Cond <- noquote(Cond)
for (i in c(1:a)) {for (j in c(1:b)) {
if (Cond) {
vide[i,j]==0
} else {
vide[i,j]=A[i,j]
}
}
but the problem is that Cond is a character matrix and I get the error message "argument is not interpretable as logical".
I am a beginner in R so maybe there is an easier way to do what I would like to do ? I tried searching on Internet but never seemed to find something appropriate to my case. Thanks for your help!
Upvotes: 0
Views: 3678
Reputation: 70653
How's this? The trick is to handle matrix is a vector. R will take care of the second dimension on the fly. What I do below is find where in A
elements from ID
appear and overwrite them with a zero.
> A
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 2 2 0 3
[2,] 1 0 0 0 0 0
[3,] 0 1 0 0 0 4
[4,] 1 0 1 0 0 4
> A[A %in% ID] <- 0
> A
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 1 0 0 0 0 0
[3,] 0 1 0 0 0 4
[4,] 1 0 1 0 0 4
Upvotes: 3