2016-12-13 30 views
1

「ラッパー」関数を書く際にいくつかの問題があります。既存の関数の引数すべてに1つの追加引数を加え、さらにいくつかの計算を行います。その追加引数は、すべてを元の関数に渡して出力を返します。eval(expr、envir、enclos)のエラー:オブジェクトが見つかりません

私が理解している限りでは、問題は、私が「ラップ」しようとしている関数が、ローカル環境で渡そうとしている引数をグローバル環境で検索しないということです。私はこの問題を解決する方法を知らない。

以下はエラーを再現する最小限のコードです。この例では、「passtheseweights」引数で計算を実行していません。なぜなら、計算が問題に関連しているとは思わないからです。

require(rpart) 
df<-car.test.frame 
wt<-runif(nrow(df)) 
wt<-wt/sum(wt) 

df<-data.frame(df, wt) 

#Attempt 1 
wrapfun<-function(formula, data, passtheseweights, ...) 
{ 
    print(passtheseweights) 
    outputmodel<-rpart(formula=formula, data=data, weights=passtheseweights, ...) 
    return(outputmodel) 
} 

wrapfun(Price~Country + Reliability + Mileage + Type + Weight + Disp. + HP, data=df, passtheseweights=df$wt, method="anova", minsplit=4) 

#Attempt 2 
wrapfun<-function(formula, data, passtheseweights, ...) 
{ 
    print(data[,passtheseweights]) 
    outputmodel<-rpart(formula=formula, data=data, weights=data[,passtheseweights], ...) 
    return(outputmodel) 
} 

wrapfun(Price~Country + Reliability + Mileage + Type + Weight + Disp. + HP, data=df, passtheseweights="wt", method="anova", minsplit=4) 

#Attempt 3, this is working.... 
wrapfun<-function(formula, data, passtheseweights, ...) 
{ 
    print(passtheseweights) 
    outputmodel<-rpart(formula=formula, data=data, weights=passtheseweights, ...) 
    return(outputmodel) 
} 

wt<-df$wt 
wrapfun(Price~Country + Reliability + Mileage + Type + Weight + Disp. + HP, data=df, passtheseweights=wt, method="anova", minsplit=4) 

#But only because the function uses wt from the global environment. The same example also works if no passtheseweights argument is passed 
wrapfun<-function(formula, data, ...) 
{ 
    print(passtheseweights) 
    outputmodel<-rpart(formula=formula, data=data, weights=passtheseweights, ...) 
    return(outputmodel) 
} 

passtheseweights<-df$wt 
wrapfun(Price~Country + Reliability + Mileage + Type + Weight + Disp. + HP, data=df, method="anova", minsplit=4) 

誰もが私がローカルpasstheseweightsを検索するためのRPARTを強制することができます方法を知っている場合は、あなたの助けが途方もいただければ幸いです!

ベスト、 CJ

+0

あなたはhttp://stackoverflow.com/a/22260104/6455166を試したことがありますか? –

+0

ありがとう!私はこのエラーメッセージに関するいくつかの質問を読んだが、別の原因があるように見えた。同じ問題を明らかにしているこの質問に私に警告してくれてありがとう。 –

答えて

0

あなたはdo.call使用することができます。

wrapfun<-function(formula, data, passtheseweights, ...) 
{ 
    outputmodel <- do.call(rpart, list(formula=formula, data=data, weights=passtheseweights, ...)) 
    return(outputmodel) 
} 
wrapfun(Price~Country + Reliability + Mileage + Type + Weight + Disp. + HP, 
     data=df, passtheseweights=df$wt, method="anova", minsplit=4) 
+0

これは完璧に動作します、ありがとう! do.callにデフォルトパラメータ "envir = parent.frame()"があるため、do.callが私のwrapfun関数の環境内のすべての引数を探すため、これが正しく動作していますか? –

+0

わかりません。私はむしろ、すべての引数(数式を含む)がリストの作成時に同じ環境で一緒に評価されるため、これが機能すると考えています。 – Roland

関連する問題