我试图创建一个封闭函数这将(?):将参数传递给一个封闭
- 过程中的一些数据,该数据的
cat()
结果,- 请求用户输入(即经由
readline()
)基于该cat()
的结果, - 然后返回的函数,其中返回的函数的参数默认中的一个是由
readline()
输入的值。
此外,我想返回的函数的参数的其余默认值是用户可解释的。也就是说,我不希望默认值是隐藏在父环境中的变量的变量名(这个规定排除了简单的参数传递)。具体来说,我希望arg()
可以返回实际评估的数字等。
我已经在下面制作了此解决方案,但感觉笨拙和尴尬。有没有更好的方法来处理这个问题?
top <- function(year=1990, n.times=NULL){
if(is.null(n.times)){
###in the real function, data would be processed here
###results would be returned via cat and
###the user is prompted return values that reflect a decision
###made from the processed data
n.times <- as.numeric(readline("how many times?"))
}
out <- function(year, n.times){
###in the real function, this is where most of the work would happen
rep(year, n.times)
}
###this entire section below is clunky.
if(!identical(names(formals()), names(formals(out)))){
stop("internal error: mismatching formals")
}
pass.formals <- setdiff(names(formals()), "n.times")
formals(out)[pass.formals] <- formals()[pass.formals]
formals(out)$n.times <- n.times
out
}
x <- top()
x
我没有答案,但强烈建议你为你的功能选择一个不同的名称。 'outer'是base-R中的矩阵创建函数。处理参数的常用方法是使用'match.arg()'函数。 –
我不会在这个玩具的例子中伤害任何东西,但我仍然修复它。 – Michael