簡體   English   中英

將字符串傳遞給filter(dplyr)的參數

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

假設我有一個條件列表:

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的過濾條件未評估為邏輯向量

您可以嘗試將條件折疊為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

但我更喜歡弗蘭克的評論

filter_將代替filter完成工作

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

更新后發表您的評論:

您可以遍歷所有長度的條件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM