dplyr:条件过滤器,字符串为列名

时间:2017-08-17 05:51:49

标签: r if-statement filter dplyr

我试图1)使用带字符串的dplyr :: filter作为列名,2)同时使用if语句。然而,虽然两者都可以正常工作,但我很难将它们组合起来,似乎是由于if语句中不能有逗号的问题。下面是dplyr 0.7.1的简化示例。

欢迎任何见解。非常感谢!!

library("dplyr")

df = data.frame(A=1:6, B=rep(c("good","bad"), 3), C=c("AA","AA","BB","BB","CC","CC"))

# with if statement but not character strings as column names - works
df %>% filter(if(T) {B %in% "good"}) 

# with character string as column names but no if statement - works
df %>% filter_at(vars("B"), any_vars(. %in% "good")) 

# doesn't work when I tried to combine the two
# Error: unexpected ',' in "df %>% filter_at(if(T){vars("B"),"
df %>% filter_at(if(T){vars("B"), any_vars(. %in% "good")})   

# tried to indicate the two parts in the if statement are really one item not two 
# by adding () or {}, and got the same complaint 
df %>% filter_at(if(T){(vars("B"), any_vars(. %in% "good"))}) 
df %>% filter_at(if(T){{vars("B"), any_vars(. %in% "good")}}) 

1 个答案:

答案 0 :(得分:1)

这有效:

df %>% filter_at(if(T){vars("B")}, any_vars(. %in% "good"))