我尝试编写一个包含dplyr :: case_when()函数的简单函数。我在https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html上阅读了dplyr文档的编程,但无法弄清楚它是如何与case_when()函数一起工作的。
我有以下数据:
data <- tibble(
item_name = c("apple", "bmw", "bmw")
)
以下列表:
cat <- list(
item_name == "apple" ~ "fruit",
item_name == "bmw" ~ "car"
)
然后我想写一个函数,如:
category_fn <- function(df, ...){
cat1 <- quos(...)
df %>%
mutate(category = case_when((!!!cat1)))
}
不幸的是,category_fn(data,cat)
在这种情况下给出了评估错误。我想获得与通过以下方式获得的输出相同的输出:
data %>%
mutate(category = case_when(item_name == "apple" ~ "fruit",
item_name == "bmw" ~ "car"))
这样做的方法是什么?
首先引用列表中的每个元素:
cat <- list(
quo(item_name == "apple" ~ "fruit"),
quo(item_name == "bmw" ~ "car")
)
然后,您的函数不必引用cat对象本身。我还改变了使用“everything else”...参数来在调用中明确引用类别参数:
category_fn <- function(df, categories){
df %>%
mutate(category = case_when(!!!categories))
}
然后函数的输出符合预期:
category_fn(data, cat)
# A tibble: 3 x 2
item_name category
<chr> <chr>
1 apple fruit
2 bmw car
3 bmw car
为了完整起见,我注意到类别列表也适用于使用基本R quote()函数定义时的函数:
cat <- list(
quote(item_name == "apple" ~ "fruit"),
quote(item_name == "bmw" ~ "car")
)
> cat
[[1]]
item_name == "apple" ~ "fruit"
[[2]]
item_name == "bmw" ~ "car"
> category_fn(data, cat)
# A tibble: 3 x 2
item_name category
<chr> <chr>
1 apple fruit
2 bmw car
3 bmw car
1)传递列表使用来自wrapr包的let
和来自问题的data
和cat
,无需以任何方式修改输入。
library(dplyr)
library(wrapr)
category_fn <- function(data, List) {
let(c(CATEGORY = toString(sapply(List, format))),
data %>% mutate(category = case_when(CATEGORY)),
subsMethod = "stringsubs",
strict = FALSE)
}
category_fn(data, cat) # test
赠送:
# A tibble: 3 x 2
item_name category
<chr> <chr>
1 apple fruit
2 bmw car
3 bmw car
1a)使用来自问题的tidyeval / rlang和data
以及cat
:
category_fn <- function(data, List) {
cat_ <- lapply(List, function(x) do.call("substitute", list(x)))
data %>% mutate(category = case_when(!!!cat_))
}
category_fn(data, cat)
给出与上述相同的结果。
2)单独传递列表组件如果您的目的是分别传递cat
的每个组件而不是cat
本身,那么这适用:
category_fn <- function(data, ...) eval.parent(substitute({
data %>% mutate(category = case_when(...))
}))
category_fn(data, item_name == "apple" ~ "fruit",
item_name == "bmw" ~ "car") # test
赠送:
# A tibble: 3 x 2
item_name category
<chr> <chr>
1 apple fruit
2 bmw car
3 bmw car
2a)如果您更喜欢tidyeval / rlang,那么这种情况很简单:
library(dplyr)
library(rlang)
category_fn <- function(data, ...) {
cat_ <- quos(...)
data %>% mutate(category = case_when(!!!cat_))
}
category_fn(data, item_name == "apple" ~ "fruit",
item_name == "bmw" ~ "car") # test