An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130516/9695670d/attachment.pl>
sapply error produced by grid search
2 messages · Patel, Shreena, Berend Hasselman
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