3

I have a data frame and I want to make make subset( or select only those rows) which satisfy the multiple conditions, Ex...

a <-data.frame(a=c("a","a","b","c","b","d"),b=c(1,2,3,4,2,3))
> a
  a b
1 a 1
2 a 2
3 b 3
4 c 4
5 b 2
6 d 3

I want to make subset where column a == a|b and column b = 2|3. Expected output

  a b
1 a 2
2 b 3
3 b 2  

I can do for one condition like

a[which(a[,"a"]=="a"),]

But is it possible to include all the multiple conditions in a single line?

Stedy
  • 7,047
  • 14
  • 54
  • 73
user1631306
  • 4,188
  • 8
  • 35
  • 67

3 Answers3

8

a[(a$a %in% c('a', 'b')) & (a$b %in% c(2, 3)), ]

JACKY Li
  • 3,221
  • 5
  • 29
  • 45
3

You can try using dplyr.

a <-data.frame(a=c("a","a","b","c","b","d"),b=c(1,2,3,4,2,3))

library(dplyr)
filter(a, (a == "a" | a == "b") & (b == 2 | b == 3))

Output:

  a b
1 a 2
2 b 3
3 b 2
Megatron
  • 14,141
  • 11
  • 84
  • 94
1

subset(a, (a %in% c('a', 'b')) & (b %in% 2:3))

jimmyb
  • 3,997
  • 2
  • 21
  • 26
  • apparently this is not a good approach: http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset – PatrickT Dec 09 '14 at 13:14