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,359
  • 14
  • 57
  • 77
user1631306
  • 4,350
  • 8
  • 39
  • 74

3 Answers3

9

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

JACKY88
  • 3,391
  • 5
  • 32
  • 48
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
  • 15,909
  • 12
  • 89
  • 97
1

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

jimmyb
  • 4,227
  • 2
  • 23
  • 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