Search code examples
rmatrixlogical-operatorssubmatrix

In R, logical operators and formulae to extract rows from a matrix


In R, let M be the matrix

     [,1] [,2] [,3]
[1,]    1    9    1
[2,]    2   12    5
[3,]    3    4    6
[4,]    6    2    4

I would like to extract a submatrix m from M applying the distinct conditions

condition 1: M[,1]<6 & M[,2]>8; condition 2: M[,1]==6 & M[,2]>1.

The submatrix m should look like

     [,1] [,2] [,3]
[1,]    1    9    1
[2,]    2   12    5   
[3,]    6    2    4

I tried to use m <- M[(M[,1]<6 & M[,2]>8) & (M[,1]==6 & M[,2]>1) ,] but it does not work; my use of& and the brackets () does not produce the right m.


Solution

  • I think you meant to use the OR operator | between your two conditions:

    M[(M[,1]<6 & M[,2]>8) | (M[,1]==6 & M[,2]>1) ,]
    #      [,1] [,2] [,3]
    # [1,]    1    9    1
    # [2,]    2   12    5
    # [3,]    6    2    4
    

    | having lower precedence than & according to ?Syntax, you could even drop all the parentheses. But feel free to keep them around if it helps you with clarity.