【问题标题】:Passing a string to an argument of filter (dplyr)将字符串传递给过滤器的参数(dplyr)
【发布时间】:2019-01-21 19:41:08
【问题描述】:

假设我有一个条件列表:

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(rlang::sym(conditions))

但不幸的是我收到了一个错误

filter_impl(.data, quo) 中的错误: 参数 2 过滤条件不计算为逻辑向量

【问题讨论】:

  • dplyr::right_join(iris, as.data.frame(input_list))?
  • 这是什么背景?您是否打算将保存为 conditions 的整个字符串作为函数的参数?
  • 它是闪亮应用程序的一部分。用户的选择被整理成一个列表 (input_list),并返回一个应用了过滤条件的数据框

标签: r string filter dplyr


【解决方案1】:

您可以尝试将条件折叠成cond1 &amp; 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

但我更喜欢弗兰克在评论中的回答

【讨论】:

  • 这个答案是 NSE 的做法吗?
  • 不 - 我不会认为这是 NSE 的做法
【解决方案2】:

filter_ 会代替filter 完成这项工作

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

更新您的评论:

无论长度如何,您都可以循环遍历适用的条件:

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

【讨论】:

  • 很抱歉,但这不起作用 - 我将我的代码用作函数的一部分,因此列表长度不固定
  • _ 函数已被 deprecated 支持 NSE
  • @Shinobi_Atobe;然后你可以遍历条件,我相应地更新了答案。 @卡米尔;我理解你的观点,但如果它现在完成工作可能会有所帮助。我一定会记住它作为未来的一个好习惯。谢谢指出!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 2021-12-02
  • 2012-07-29
  • 2015-07-01
  • 2013-08-17
相关资源
最近更新 更多