我正在尝试 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")}})
最佳答案
这个有效:
df %>% filter_at(if(T){vars("B")}, any_vars(. %in% "good"))
关于r - dplyr:以字符串作为列名的条件过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727508/