0

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.

niton
  • 8,771
  • 21
  • 32
  • 52
Avitus
  • 734
  • 2
  • 14
  • 27

1 Answers1

4

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.

flodel
  • 87,577
  • 21
  • 185
  • 223
  • definitly better: the & operator was the source of problems, not the brackets. Thanks a lot, Avitus – Avitus May 22 '13 at 12:33