【发布时间】:2017-12-21 09:43:45
【问题描述】:
假设我想以编程方式过滤 starwars 数据框。这是一个简单的示例,可让我根据家园和物种进行过滤:
library(tidyverse)
# a function that allows the user to supply filters
filter_starwars <- function(filters) {
for (filter in filters) {
starwars = filter_at(starwars, filter$var, all_vars(. %in% filter$values))
}
return(starwars)
}
# filter Star Wars characters that are human, and from either Tatooine or Alderaan
filter_starwars(filters = list(
list(var = "homeworld", values = c("Tatooine", "Alderaan")),
list(var = "species", values = "Human")
))
但这并不允许我指定高度过滤器,因为我已经在 .vars_predicate 的 filter_at() 中硬编码了 %in% 运算符,并且高度过滤器将使用 @ 之一987654327@、>=、<、<= 或 == 运营商
编写filter_starwars() 函数的最佳方式是什么,以便用户可以提供足够通用的过滤器来过滤任何列并使用任何运算符?
NB 使用现在已弃用的filter_() 方法,我可以传递一个字符串:
filter_(starwars, "species == 'Human' & homeworld %in% c('Tatooine', 'Alderaan') & height > 175")
但同样,这已被弃用。
【问题讨论】:
-
使用
filter_- stackoverflow.com/questions/38493031/…讨论此问题的相关问题