私は、次のような囲み関数を作成しようとしています:
- 一部のデータを処理し、
cat()
そのデータの結果、readline()
その結果に基づいて (つまり、 経由で)cat()
ユーザー入力を要求します。- 次に、返された関数の引数のデフォルトの 1 つが によって入力された値である関数を返します
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