eval(expr,envir,enclos)中的错误:找不到对象

时间:2016-12-13 11:39:25

标签: r function wrapper

我在编写“包装器”时遇到了一些困难。 function,应该获取现有函数的所有参数加上一个附加参数,然后对该附加参数执行一些计算,将所有内容传递给原始函数并返回输出。

据我所知,问题在于我正在尝试的功能包装'不会搜索我试图传入本地环境但在全球环境中的参数。我不知道如何解决这个问题。

下面是我对再现错误的最小代码的尝试。在这个例子中,我没有对' 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)

如果有人知道我如何强制rpart在本地搜索passtheseweights,那么您的帮助将会非常感激!

最佳, CJ

1 个答案:

答案 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)