ネストされた関数呼び出しと引数評価の操作方法を理解するのに苦労しています。
簡単な例を次に示します。topfunction
1 つの数値引数を持つトップレベル関数があります。の中で、引数が の中で定義された関数への呼び出しであるtopfunction
別の関数を呼び出します。lowerfunction
lowerfunction
topfunction<-function(x){
lowerfunction(myfun(first=x[1],second=x[2],third=if(length(x)>2) x[3]))
}
lowerfunction<-function(mycall){
myfun<-function(first,second=0,third=NULL){
print(first)
print(second)
print(third)
}
mc<-match.call(definition = myfun, call = match.call()[[2]])
eval(mc)
}
内部でlowerfunction
は、関数呼び出しを でキャプチャし、呼び出しmatch.call
を評価しようとします。しかし、 variablex
は の環境でのみ定義されているためtopfunction
、評価は失敗します。
topfunction(x=1:3)
Error in print(first) : object 'x' not found
私はラインを変更できることを知っています
lowerfunction(myfun(first=x[1],second=x[2],third=if(length(x)>2) x[3]))
なので
lowerfunction(substitute(myfun(first=x[1],second=x[2],third=if(length(x)>2) x[3])))
でtopfunction
、しかし私の実際のアプリケーションでtopfunction
は はユーザーによって構築されるため、解決策はレベルlowerfunction
またはmyfun
レベルで何らかの形で発生するはずです。しかし、彼らはすでに に関する情報を失っているのでx
、それが達成できるかどうかわかりませんか?
実際のアプリケーションでは、topfunction
は を使用してモデルを構築し、lowerfunction
その可能性を計算しますが、 の引数lowerfunction
は、 を介して評価される関数呼び出しを含むことができる式eval
です。これらの関数は、 内でのみ定義されますlowerfunction
。また、lowerfunction
直接呼び出すこともできます。
x<-1:3
lowerfunction(myfun(first=x[1],second=x[2],third=if(length(x)>2) x[3]))
# or
lowerfunction(myfun(first=x1,second=2)
したがってx
、の引数リストに追加するソリューションlowerfunction
は、一般的に適用できません。
したがって、問題は、ある環境 (パッケージ名前空間、またはこの場合は の環境) からeval
の定義を取得し、他の環境、つまり の環境での引数を評価する必要があることです。myfun
lowerfunction
myfun
topfunction