I'm trying to wrap the car::boxCox function into a homemade function so I can mapply it to a list of datasets. I'm using the boxCox function from the car package and not the MASS package because I want to use the family="yjPower". My problem is weird and it's either something fondamental I don't understand or some kind of bug. Here is a reproducible example:
library(car)
le.mod <- function(val.gold,val.bad){
donn <- data.frame(val.gold,val.bad)
res.lm <- lm(val.gold ~ val.bad, data=donn)
bcres <- boxCox(res.lm, family="yjPower", plotit=F)
lambda <- bcres$x[which.max(bcres$y)]
donn$val.bad.t <- donn$val.bad^lambda
res.lm <- lm(val.gold ~ val.bad.t, data=donn)
list(res.lm=res.lm, lambda = lambda)
}
xx <- runif(1000,1,100)
xxt1 <- xx^0.6 + runif(1000,1,10)
yy <- 2*xx + 10 + rnorm(1000,0,2)
le.mod(yy,xxt1)
This gives me the error message:
## Error in is.data.frame(data) : object 'donn' not found
I pin-pointed the problem to the line:
bcres <- boxCox(res.lm, family="yjPower", plotit=F)
boxCox is suppose to be able to take a lm class object, it just doesn't find the associated data that were created 2 lines before.
It works well outside of the function le.mod(). It's probably a problem related to environment management, the boxCox fonction looking for "donn" in the global environment but not finding it and for a reason I ignore not looking for it in the function specific environment.
Anybody have an idea to fix this or explain to me what I don't understand here? I've been turning my head over this problem for days and I can't get it working.
Thanks
I've found the answer (!), however I can't understand the reason of the behaviour so if somebody have an explanation, don't hesitate to post it.
The solution by adding y=TRUE
in the second line of the function:
res.lm <- lm(val.gold ~ val.bad, data=donn,y=TRUE)
For some reasons, this allows it to get throught.