Seen
Seen

Reputation: 4194

compare two matrices with criteria in R

I have two matrices

A
2 1 0
0 1 6
1 0 0
B 
1 1 3
4 2 8
2 0 1

I want to find out the elements comparing A and B satisfying the following criteria:

if A[i,j] =0 and B[i,j]>0

So my result matrix should be

C
0 0 3
4 0 0
0 0 1

What is a proper way to do this except for a for loop?

Upvotes: 1

Views: 7032

Answers (3)

IRTFM
IRTFM

Reputation: 263499

Regular logical and arithmetic operators act element wise on matrices in R. Only the %*% and kronecker operators do matrix multiplication. Furthermore you can index matrixes using the "[" and "[<-" functions:

> C <- B
> C[!( A==0 & B >0) ] <- 0
> C
     [,1] [,2] [,3]
[1,]    0    0    3
[2,]    4    0    0
[3,]    0    0    1

Upvotes: 6

Andrie
Andrie

Reputation: 179588

Use simple comparison operators on the matrices.

Recreate the data, using:

A <- as.matrix(read.table(text="
2 1 0
0 1 6
1 0 0"))

B <- as.matrix(read.table(text="
1 1 3
4 2 8
2 0 1"))

Perform the comparison:

A==0 & B>0
        V1    V2    V3
[1,] FALSE FALSE  TRUE
[2,]  TRUE FALSE FALSE
[3,] FALSE FALSE  TRUE

And then use ifelse:

ifelse(A==0 & B>0, B, 0)
     V1 V2 V3
[1,]  0  0  3
[2,]  4  0  0
[3,]  0  0  1

Upvotes: 1

Sacha Epskamp
Sacha Epskamp

Reputation: 47642

I wasn't sure which element you wanted if this was true so I assumed the sum:

A <- matrix(c(2, 1, 0, 0, 1, 6, 1, 0, 0),3,3,byrow=TRUE)
B  <- matrix(c(1, 1, 3, 4, 2, 8, 2, 0, 1),3,3,byrow=TRUE)

C <- ifelse(A==0 & B>0, A+B, 0)
     [,1] [,2] [,3]
[1,]    0    0    3
[2,]    4    0    0
[3,]    0    0    1

But clearer might be using which:

which(A==0 & B>0, arr.ind=TRUE)
     row col
[1,]   2   1
[2,]   1   3
[3,]   3   3

edit:

Note that the correct way of indexing a matrix is A[i,j] instead of A[i][j].

Upvotes: 5

Related Questions