While running model0
found below I got an error message “ Error in eval(expr, envir, enclos) : could not find function "Lag" . Before posting this message I have scanned this forum and the web, but could not find relevant solution. I believe the error in my model is not probably due to Lag
function as other models (1 and 2) shown below could run without encountering any problem.
My main motive was to run a GAM model by looping through a list of explanatory variables and their lags.
library(quantmod)
library(gamair)
library(mgcv)
data(chicago)
names(chicago)
varlist0 <- c("pm10median", "pm25median", "o3median", "so2median")
model0<- lapply(varlist0, function(x) {
gam(substitute(death ~ s(time,bs="cr",k=200)+ s(tmpd,bs="cr") + Lag(i,0:4) , list(i = as.name(x))),family=quasipoisson,na.action=na.omit, data=chicago)
})
Gam + Lag with no error message:
model1<- gam(death ~ s(time,bs="cr",k=200)+ s(tmpd,bs="cr") + Lag(pm10median, 0:4),family=quasipoisson,na.action=na.omit, data=chicago)
Lm with Lag and no error message:
hsb2 <- read.csv("http://www.ats.ucla.edu/stat/data/hsb2.csv")
varlist <- names(hsb2)[8:11]
models <- lapply(varlist, function(x) {
lm(substitute(read ~ Lag(i,0:4) , list(i = as.name(x))), data = hsb2)
})
I am unable to decipher the cause of this error. What have I done wrong in the first model?
I can't say the exact cause, but it has something to do with the environment in which mgcv
is evaluating the formula. A safer approach than substitute
is to do something like the following:
varlist0 <- c("pm10median", "pm25median", "o3median", "so2median")
model0 <- lapply(varlist0,function(v) {
f <- sprintf("death ~ s(time,bs='cr',k=200)+s(tmpd,bs='cr') + Lag(%s,0:4)",v)
gam(as.formula(f),family=quasipoisson,na.action=na.omit,data=chicago)
})