我想使用tidy 評估來撰寫多個完全靈活的過濾條件。這個 Stackoverflow Question已經解決了一個相關但不太復雜的問題。以下代碼(改編自上述其他問題)正在運行。它將兩個過濾條件應用于 gapminder 資料集,并回傳過濾后的資料。
library(tidyverse)
library(gapminder)
my_filter <- function(df, cols, vals){
paste_filter <- function(x, y) quo(!!sym(x) %in% {{y}})
fp <- pmap(list(cols, vals), paste_filter)
filter(df, !!!fp)
}
cols <- list("country", "year")
vals = list(c("Albania", "France"), c(2002, 2007))
gapminder %>% my_filter(cols, vals)
問題:到目前為止,此解決方案僅限于一種型別的過濾器運算子 ( %in%)。我想擴展這種方法以接受任意型別的運算子 ( ==, %in%, >, ...)。預期的功能my_filter應該處理以下內容:
cols <- list("country", "year")
ops <- list("%in%", ">=")
vals = list(c("Albania", "France"), 2007))
gapminder %>% my_filter(cols, ops, vals)
我腦海中的用例是閃亮的應用程式。使用這樣的功能,我們可以更輕松地讓用戶對資料集的變數設定任意過濾條件。
uj5u.com熱心網友回復:
創建呼叫串列并將它們拼接到:
library(dplyr)
library(gapminder)
cols <- list("country", "year")
ops <- list("%in%", ">=")
vals <- list(c("Albania", "France"), 2007)
# Assumes LHS is the name of a variable and OP is
# the name of a function
op_call <- function(op, lhs, rhs) {
call(op, sym(lhs), rhs)
}
my_filter <- function(data, cols, ops, vals) {
exprs <- purrr::pmap(list(ops, cols, vals), op_call)
data %>% dplyr::filter(!!!exprs)
}
gapminder %>% my_filter(cols, ops, vals)
#> # A tibble: 2 × 6
#> country continent year lifeExp pop gdpPercap
#> <fct> <fct> <int> <dbl> <int> <dbl>
#> 1 Albania Europe 2007 76.4 3600523 5937.
#> 2 France Europe 2007 80.7 61083916 30470.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318548.html
上一篇:為什么Tesseract的邊界框未在影像文本上對齊?
下一篇:請求問題(獲取)
