简体   繁体   English

将字符串传递给filter(dplyr)的参数

[英]Passing a string to an argument of filter (dplyr)

let's say I have a list of conditions: 假设我有一个条件列表:

input_list <- list(Species = "setosa",
                   Petal.Width = 0.2)

I can turn this list into a string: 我可以将此列表转换为字符串:

x <- map(input_list, ~ paste0( " == ", "'", .[[1]], "'"))
conditions <- paste(names(x), x, collapse = ", ")


conditions
> [1] "Species  == 'setosa', Petal.Width  == '0.2'"

I would like to pass this string as conditions to filter : 我想将此字符串作为要过滤的条件:

iris %>% filter(rlang::sym(conditions))

But unfortunately I get an error 但是不幸的是我得到一个错误

Error in filter_impl(.data, quo) : Argument 2 filter condition does not evaluate to a logical vector filter_impl(.data,quo)中的错误:参数2的过滤条件未评估为逻辑向量

You can try collapsing your conditions into a string of form cond1 & cond2 and use eval(parse(text=...)) 您可以尝试将条件折叠为cond1 & cond2形式的字符串,然后使用eval(parse(text=...))

input_list <- list(Species = "setosa",
                   Petal.Width = 0.2)

x <- map(input_list, ~ paste0( " == ", "'", .[[1]], "'"))
conditions <- paste(names(x), x, collapse = " & ")
conditions
# [1] "Species  == 'setosa' & Petal.Width  == '0.2'"

iris %>% filter(eval(parse(text = conditions)))
   # Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 2           4.9         3.0          1.4         0.2  setosa
# 3           4.7         3.2          1.3         0.2  setosa
# 4           4.6         3.1          1.5         0.2  setosa
# 5           5.0         3.6          1.4         0.2  setosa
# 6           5.0         3.4          1.5         0.2  setosa
# 7           4.4         2.9          1.4         0.2  setosa
# 8           5.4         3.7          1.5         0.2  setosa
# 9           4.8         3.4          1.6         0.2  setosa
# etc

But I prefer Frank's answer in comment 但我更喜欢弗兰克的评论

filter_ would do the job instead of filter filter_将代替filter完成工作

conds <- stringr::str_split(conditions, ", ")
iris %>% filter_(conds[[1]][1], conds[[1]][2])

Update following up your comment: 更新后发表您的评论:

You can loop through the conditions which would work regardless of length: 您可以遍历所有长度的条件:

for(i in conds[[1]]) {
  iris <- iris %>% filter_(i)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM