r - 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 =
#> ^
解决方案
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")
推荐阅读
- mongodb - MongoDB 错误“$filter 的输入必须是数组而不是对象”
- git - 从 git 中删除 .files 作为新添加的文件
- java - 使用linux在javadoc中创建所有类的菜单
- python - Numpy where条件满足时必须修改原始值,如果不是原始值必须保留
- firebase - 使用数组格式将数据从flutter添加到firestore
- python - 数据框中的不同时间格式
- python - Python - 如何从 GraphQL api 获取 JSON?
- multithreading - 为什么 QCoreApplication::processEvents() 会阻塞 QThread::wait()?
- react-native - 检查元素中的 React-Native 白色区域
- db2 - 如何使用 Jupyter Notebook 连接到 db2 而不会遇到 sql 错误