Error in eval(expr, envir, enclos) : object not found
<p>I am experiencing some difficulties in writing a 'wrapper' function, which should take all the arguments for an existing function plus one additional argument, then perform some calculations on that additional argument, pass everything to the original function and return the output.</p>

<p>To the best of my understanding, the problem is that the function I am trying to 'wrap' does not search for the argument I'm trying to pass in the local environment, but in the global environment. I don't know how to solve this problem.</p>

<p>Below is my stab at a minimal code that reproduces the error. In this example I am not performing any calculations on the 'passtheseweights' argument, because I don't think the calculations are relevant for the question.</p>

<pre><code>require(rpart)
df&lt;-car.test.frame
wt&lt;-runif(nrow(df))
wt&lt;-wt/sum(wt)

df&lt;-data.frame(df, wt)

#Attempt 1
wrapfun&lt;-function(formula, data, passtheseweights, ...)
{
  print(passtheseweights)
  outputmodel&lt;-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&lt;-function(formula, data, passtheseweights, ...)
{
  print(data[,passtheseweights])
  outputmodel&lt;-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&lt;-function(formula, data, passtheseweights, ...)
{
  print(passtheseweights)
  outputmodel&lt;-rpart(formula=formula, data=data, weights=passtheseweights, ...)
  return(outputmodel)
}

wt&lt;-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&lt;-function(formula, data, ...)
{
  print(passtheseweights)
  outputmodel&lt;-rpart(formula=formula, data=data, weights=passtheseweights, ...)
  return(outputmodel)
}

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

<p>If anyone knows how I can force rpart to search for passtheseweights locally, your help would be tremendously appreciated!</p>

<p>Best,
CJ</p>