测试使用enquo()作为NULL参数的函数 [英] Testing a function that uses enquo() for a NULL parameter

查看:103
本文介绍了测试使用enquo()作为NULL参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建数据框的函数,但是在过程中会更改名称。我正在尝试使用dplyr quosures处理空列名称。我的测试套件如下所示:

I have a function which creates dataframe, but changes names in the process. I am trying to handle empty column names with dplyr quosures. My test suite looks like this:

dataframe <- data_frame(
  a = 1:5,
  b = 6:10
)

my_fun <- function(df, col_name, new_var_name = NULL) {
  target <- enquo(col_name)

  c <- df %>% pull(!!target) * 3 # here may be more complex calculations

  # handling NULL name
  if (is.null(new_var_name)) {
    new_name <- quo(default_name)
  } else{
    new_name <- enquo(new_name)
  }

  data_frame(
    abc = df %>% pull(!!target),
    !!quo_name(new_name) := c
  )
}

如果我这样调用我的函数:

And if I call my function like this:

my_fun(dataframe, a)

我将获得默认名称:

# A tibble: 5 x 2
    abc default_name
  <int>        <dbl>
1     1            3
2     2            6
3     3            9
4     4           12
5     5           15

如果我尝试传递名称,则会收到错误消息:

And if I'm trying to pass name I get error:

my_fun(dataframe, a, NEW_NAME)
Error in my_fun(dataframe, a, NEW_NAME) : object 'NEW_NAME' not found

我在哪里错了?

推荐答案

这个问题与 quo enquo 返回不同的东西,这实际上是在真正想要评估对象之前。如果要使用 browser()逐步执行函数,则会在 if(is.null(new_var_name ))语句。

This problem doesn't really have to do with quo and enquo returning different things, it's really about evaluating objects before you really want to. If you were to use the browser() to step through your function, you'd see the error occurs at the if (is.null(new_var_name)) statement.

执行 is.null(new_var_name)时,您正在评估作为 new_var_name 传递的变量,因此现在 enquo 为时已晚。这是因为 is.null 需要查看变量的值,而不仅仅是变量名本身。

When you do is.null(new_var_name), you are evaluating the variable passed as new_var_name so it's too late to enquo it. That's because is.null needs to look at the value of the variable rather than just the variable name itself.

一个不评估传递给该函数的参数,但检查是否存在 missing()

A function that does not evaluate the parameter passed to the function but checks to see if it is there is missing().

my_fun <- function(df, col_name, new_var_name=NULL) {
  target <- enquo(col_name)

  c <- df %>% pull(!!target) * 3 # here may be more complex calculations

  # handling NULL name
  if (missing(new_var_name)) {
    new_name <- "default_name"
  } else{
    new_name <- quo_name(enquo(new_var_name))
  }

  data_frame(
    abc = df %>% pull(!!target),
    !!new_name := c
  )
}

然后您可以同时运行这两个

Then you can run both of these

my_fun(dataframe, a)
my_fun(dataframe, a, NEW_NAME)

这篇关于测试使用enquo()作为NULL参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆