select from two matrices based on the lowest?

Viewed 37

I have these:

mat1 <- matrix(runif(100),ncol=5)
mat11 <- matrix(runif(100),ncol=5)

mat2 <- matrix(runif(100),ncol=5)
mat22 <- matrix(runif(100),ncol=5)

lets take example :

My output 2 matrices res1 take value from mat1 or mat2 which correspond to lowest between mat11[1,1] and mat22[1,1] and return this lowest value as res11

example :

  > mat1[1,1]
          [1] 0.09302976
  > mat11[1,1]
          [1] 0.8775101
  > mat2[1,1]
          [1] 0.6785858
   > mat22[1,1]
          [1] 0.8857934

desired output :

       res1[1,1]= 0.09302976# was selected because the corresponding mat11 value (0.8775101) was lower than corresponding value to mat22[1,1] 
       res11[1,1]= 0.8775101

How to apply this to the whole matrix ?

1 Answers

We can use pmin

pmin(mat1, mat11)

Or if it is related to another matrix

ifelse(mat11 < mat22, mat1, mat2)
Related