2012-09-28 92 views
2

我有一個數據幀,並我想使化妝子集(或只選擇那些行),其滿足多個條件,實施例...數據幀的選擇指數statisfying多個條件中的R

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 

我想要在列a == a | b和列b = 2 | 3中創建子集。預計輸出

a b 
1 a 2 
2 b 3 
3 b 2 

我可以像

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

一個條件做但是,它可能包括在單行所有的多個條件?

回答

1

子集(A,(A以%C(% 'A', 'B'))&(以%2 B%:3))

+0

顯然,這不是一個好辦法: http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset – PatrickT

8

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

2

您可以嘗試使用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)) 

輸出:

a b 
1 a 2 
2 b 3 
3 b 2