rlang :: new_function中的未引用参数(对于函数工厂)

时间:2018-09-15 23:12:03

标签: r rlang

我想为通过'Open the workbook and store a reference to the data sheet Set wbkSrc = Workbooks.Open(strFilePath) On Error Resume Next Set wksSrc = wbkSrc.Worksheets("data") '<~ change based on your Sheet name** On Error GoTo 0 If wksSrc Is Nothing Then ' <-- check is worksheet object is nothing MsgBox "worksheet data doesn't exist", vbCritical Exit Sub End If 创建的函数指定一个自定义参数。为此,我需要将参数传递给rlang::new_function的{​​{1}}参数。

我假设args应加引号/不加引号。到目前为止,这是我尝试过的:

new_function

所需的输出将是:

named_arg


以下是我尝试过但无法使用的一种方法:

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")

1 个答案:

答案 0 :(得分:3)

我们可以使用substitute来获取未引用的参数并更改'exprs'的names

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")

以防万一,我们使用rlang,然后用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")