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

查看:16
本文介绍了测试使用 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)

我按预期获得默认名称:

I get default name as intended:

# 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

我哪里错了?

推荐答案

这个问题实际上与 quoenquo 返回不同的东西无关,它真的关于在你真正想要之前评估对象.如果您要使用 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
  )
}

然后你可以运行这两个

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

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

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