如何通过多种因素选择多行?

时间:2018-06-14 10:07:42

标签: r dataframe

我有一些数据框,我想根据某些因素选择行。我现在能做的是分别构建子数据帧,然后将它们组合在一起。这是另一种有效的方法吗?

For instance, I want to pick the rows which in a1 is "F" and the rows which a4 is "John" together.
a1 <- c("F","M","F","M","F","F")
a2 <- c("S","S","S","T","T","S")
a3 <- c(250, 66, 95, 2, 1, 4)
a4 <- c("John","Annie","King","John","Tom","Lily")
df <- data.frame(a1,a2,a3,a4)
df2 <- df[df$a1 == "F",]   # sub-dataframe which a1 is "F"
df3 <- df[df$a4 == "John",]  # sub-dataframe which a4 is "John"
rbind(df2,df3) # combine them together
#ideal result
> rbind(df2,df3)
a1 a2  a3   a4
1   F  S 250 John
3   F  S  95 King
5   F  T   1  Tom
6   F  S   4 Lily
11  F  S 250 John
4   M  T   2 John

1 个答案:

答案 0 :(得分:0)

使用base R可以通过插入'OR'运算符

来实现
df[df$a1 == "F" | df$a4 == "John",]

另一种方法是使用dplyr包:

df %>% filter(a1 == "F" | a4 == "John")