在R中,我试图将参数从外部函数传递给内部函数,然后在内部函数中对它们进行求值。这失败了,大概是因为传递参数时未对它们进行求值。
这里有两个例子;一个使用match.call()来获取外部函数的参数并将其传递,另一个使用手动将外部函数的参数绑定在列表中,然后调用内部函数。我怀疑我无法掌握match.call()和惰性计算的某些复杂性。有解决这个问题的优雅方法吗?
# Use match.call to pass arguments to inner_function
outer_fun_a <- function(formula, data){
args <- as.list(match.call())[-1]
mods <- names(get_all_vars(formula, data = data))[-1]
inner_function(mods, args)
}
# Make a list of the arguments of outer_fun_b
outer_fun_b <- function(formula, data){
args <- list(formula = formula, data = data)
mods <- names(get_all_vars(formula, data = data))[-1]
inner_function(mods, args)
}
inner_function <- function(modvars, args){
args$formula <- update(args$formula, paste0("~ ", paste(modvars, collapse = " + ")))
do.call(lm, args)
}
df <- iris
# This fails, because the arguments in args have not been evuated
outer_fun_a(as.formula(paste0("Sepal.Length ~ ", paste(names(df)[2:5], collapse = " + "))),
df)
# This succeeds
outer_fun_b(as.formula(paste0("Sepal.Length ~ ", paste(names(df)[2:5], collapse = " + "))),
df)