rmatrixmaxcombiners

Have 3 matrices of same dimensions - I want to get the highest value of each cell of the three different matrices


Basically I have 3 matrices of the same dimensions. They only consist of values 0 , 1, 2 ,3. I would like to create a new matrix that takes the highest value from each of the corresponding matrices.

For example, if the first row of the matrices are as follows:

A: 0 1 0 0 1
B: 2 0 0 2 0
C: 0 3 0 3 0

Final: 2 3 0 3 1

I was trying to do a for function with apply but I couldn't get it working.

Edit: I think pmax is the function to do according to the comments.. Thanks! Im am just starting out and learning about R so sorry if this is a simple question.


Solution

  • Here's some sample data:

    m1 <- matrix(sample(0:3, 12, replace = TRUE), 4)
    m2 <- matrix(sample(0:3, 12, replace = TRUE), 4)             
    m3 <- matrix(sample(0:3, 12, replace = TRUE), 4)
    

    And the result

    pmax(m1, m2, m3)
    #      [,1] [,2] [,3]
    # [1,]    3    1    3
    # [2,]    2    3    1
    # [3,]    1    3    3
    # [4,]    3    3    3