2

我正在编写一个函数,其中输入是另一个函数的参数和名称。我想将这些参数和函数名转换为未计算的表达式或调用。例如,如果这是对函数的调用:

huh_fun(
  data = mtcars
  method = lm,
  formula = hp ~ mpg,
  method.args = list(weights = drat, subset = rep(TRUE, 32)) # list of additional arguments
)

我希望该函数返回以下未评估的表达式/调用:

lm(hp ~ mpg, data = mtcars, weights = drat, subset = rep(TRUE, 32))

我已经成功引用了data=,method=formula=参数并将它们组合成一个调用。但无法弄清楚如何引用method.args=参数,并将列表元素添加到函数参数中。任何和所有的指针都表示赞赏。谢谢~

4

2 回答 2

1

在“huh_fun”中固定参数名称后,我们可以使用“语言”对象构造一个未评估的调用:

huh_fun = function(data, method, formula, method.args)
{
    ans = c(list(substitute(method), 
                 substitute(formula), 
                 data = substitute(data)), 
            as.list(substitute(method.args))[-1])
    as.call(ans)
}

huh_fun(
    data = mtcars,
    method = lm,
    formula = hp ~ mpg,
    method.args = list(weights = drat, subset = rep(TRUE, 32)))
#lm(hp ~ mpg, data = mtcars, weights = drat, subset = rep(TRUE, 
#    32))
于 2019-12-21T09:47:10.290 回答
0

你可以deparse(substitute(x))paste它一起使用。使用 生成呼叫str2lang

huh_fun <- function(data, method, formula, method.args) {
  str2lang(paste0(deparse(substitute(method)), "(", deparse(substitute(formula)), ", ",
         "data = ", deparse(substitute(data)), ", ", 
         gsub("list\\((.*)\\)$", "\\1", deparse(substitute(method.args))),
         ")"))
}

结果

huh_fun(
  data=mtcars,
  method=lm,
  formula=hp ~ mpg,
  method.args=list(weights=drat, subset=rep(TRUE, 32)) # list of additional arguments
)

# lm(hp ~ mpg, data = mtcars, weights = drat, subset = rep(TRUE, 32))
于 2019-12-21T05:14:53.803 回答