首页 > 解决方案 > Unquote arguments in rlang::new_function (for function factory)

问题描述

I would like to specify a custom argument for a function created via rlang::new_function. For this I need to pass an argument to the args-argument of new_function.

I assume the named_arg should be quoted/ unquoted. This is what I have tried so far:

library(rlang)

function_factory <- function(named_arg) {

  new_function(
    exprs(named_arg =,... = ),
    expr(print("hello world")),
    caller_env()
  )
}

fun1 <- function_factory(arg1)
fun1

#> function (named_arg, ...) 
#> print("hello world")

The desired output would be:

#> function (arg1, ...) 
#> print("hello world")


Below is one approach I have tried, but didn't work:

function_factory <- function(named_arg) {
  named_arg_quo <- enquo(named_arg)

  new_function(
    exprs(!!named_arg_quo =,... = ),
    expr(print("hello world")),
    caller_env()
  )
}
#> Error: <text>:21:27: unexpected '='
#> 20:   new_function(
#> 21:     exprs(!!named_arg_quo =
#>                               ^

标签: rrlang

解决方案


We could use substitute to grab the unquoted argument and change the names of the 'exprs`

function_factory <- function(named_arg) {

  nm1 <- deparse(substitute(named_arg))
  exp1 <- exprs(named_arg =,... = )
  names(exp1)[1] <- nm1
  new_function(
     exp1,
     expr(print("hello world")),
     caller_env()
   )

}

function_factory(arg1)
#function (arg1, ...) 
#print("hello world")

In case, we are using rlang, then convert to string with quo_name

library(rlang)
function_factory <- function(named_arg) {

  nm1 <- quo_name(enquo(named_arg))
  exp1 <- exprs(named_arg =,... = )
  names(exp1)[1] <- nm1
  new_function(
     exp1,
     expr(print("hello world")),
     caller_env()
   )

}

function_factory(arg1)
#function (arg1, ...) 
#print("hello world")

推荐阅读