[R] sapply error produced by grid search
Berend Hasselman
bhh at xs4all.nl
Thu May 16 18:48:18 CEST 2013
On 16-05-2013, at 17:31, "Patel, Shreena" <s.patel10 at lancaster.ac.uk> wrote:
> Dear R User,
>
> I'm trying to perform a grid-search for the ML estimator of the Box-Cox parameter for a linear mixed model. However using sapply to perform the grid search returns an error message. Here's a small example to demonstrate:
>
> library(lme4)
>
> # Function to fit model for a given lambda:
> bc.fit <- function(lam,X,Z,Y){
> ybar <- exp(mean(log(Y)))
> if(lam==0){
> w <- ybar*log(Y)
> } else {
> w <- (Y^lam-1)/(lam*ybar^(lam-1))
> }
> bc.mod <- lmer(w~X+(1|Z))
> as.numeric(logLik(bc.mod))
> }
>
> # Simulate data
> x <- runif(1000)
> z <- sample(1:100,1000,T)
> b <- rnorm(100)[z]
> y <- rnorm(1000,20+0.5*x+b,2)
>
> # Perform search
> lambda <- 1:10/10
> sapply(lambda,bc.fit,X=x,Z=z,Y=y)
>
> Produces the error:
> Error in get(as.character(FUN), mode = "function", envir = envir) :
> object 'lambda' of mode 'function' was not found
>
> However a single run works fine - bc.fit(lambda[1],x,z,y)
>
> Other people appear to have had similar errors, caused by naming variables after existing functions, however I don't think that's the problem here. Any advice would be appreciated, thank you!
It is the problem.
The first argument of sapply is X. Your function bc.fit has an argument X which you explicitly set to x.
So sapply takes lambda as the second argument which is FUN (function).
So rename your bc.fit arguments to something else: e.g. (x,y,z) or (X1,Y1,Z1).
And reread the documentation of sapply. It's all there.
Berend
More information about the R-help
mailing list