Comparing two matrices (A & B) and deriving a new matrix C with cij = min (aij, bij)

The title is pretty clear, but I'm trying to take two matrices A and B and output a matrix C that has the minimum elements of the two matrices.

cij = min (aij, bij)

This is how I view it this way:

C <- matrix(ncol = ncol(A), nrow = nrow(A), 0)
for (i in 1:ncol(C)) {
    Y <- rbind(A[i,], B[i,])
    C[i,] <- apply(Y, 2, min)
}

      

However, I was hoping it could be vectorized, but I can't think of how to do it. I didn't find anything, so if anyone has any ideas I'd really appreciate it.

Thank!

+3


source to share


2 answers


See ?pmin

(parallel minimum):



R> A <- matrix(1:4, 2, 2)
R> B <- matrix(c(5, 1, 1, 6), 2, 2)
R> A
     [,1] [,2]
[1,]    1    3
[2,]    2    4
R> B
     [,1] [,2]
[1,]    5    1
[2,]    1    6
R> pmin(A, B)
     [,1] [,2]
[1,]    1    1
[2,]    1    4

      

+11


source


Try

C <- A
C[A>B] <- B[A>B]

      



This is less straightforward but will work. Demonstration:

> A <- matrix(1:4, 2, 2)
> B <- matrix(c(5, 1, 1, 6), 2, 2)
> C <- A
> C[A>B] <- B[A>B]
> 
> A
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> B
     [,1] [,2]
[1,]    5    1
[2,]    1    6
> C
     [,1] [,2]
[1,]    1    1
[2,]    1    4

      

0


source







All Articles