进行整洁的评估编程

进行整洁的评估编程

本文介绍了使用 dplyr::case_when 进行整洁的评估编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个简单的函数来封装 dplyr::case_when() 函数.我阅读了 上的 programming with dplyr 文档https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html 但无法弄清楚如何使用 case_when() 函数.

I try to write a simple function wrapping around the dplyr::case_when() function. I read the programming with dplyr documentation on https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html but can't figure out how this works with the case_when() function.

我有以下数据:

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) 在这种情况下给出了评估错误.我想获得与通过以下方式获得的输出相同的输出:

Unfortunately category_fn(data,cat) gives an evaluation error in this case. I would like to obtain the same output as the output obtained by:

data %>%
   mutate(category = case_when(item_name == "apple" ~ "fruit",
                               item_name == "bmw" ~ "car"))

有什么方法可以做到这一点?

What is the way to do this?

推荐答案

首先引用列表中的每个元素:

Quote each element of your list first:

cat <- list(
  quo(item_name == "apple" ~ "fruit"),
  quo(item_name == "bmw" ~ "car")
)

您的函数不必引用 cat 对象本身.我还更改了其他一切"...参数的使用,以在调用中明确引用类别参数:

Your function does not then have to quote the cat object itself. I have also changed the use of the "everything else" ... argument to refer to the category argument explicitly in the call:

category_fn <- function(df, categories){
  df %>%
    mutate(category = case_when(!!!categories))
}

函数的输出就如预期的那样:

The output of the function is then as expected:

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() 函数定义时也适用于您的函数:

For completeness, I note that the category list works with your function when defined using the base R quote() function too:

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

这篇关于使用 dplyr::case_when 进行整洁的评估编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 19:08