0
votes

I've been trying to fit multiple GAMs using the package mgcv within a function, and crudely select the most appropriate model through model selection procedures. But my function runs the first model then doesn't seem to recognise the input data dat again.

I get the error

Error in is.data.frame(data) : object 'dat' not found.

I think this is a scoping problem and I've looked here, and here for help but cannot figure it out.

Code and data are as follows (hopefully reproducible): https://github.com/cwaldock1/Help/blob/master/test_gam.csv

library(mgcv)

# Function to fit multiple models 
best.mod <- function(dat) {

# Set up control structure
ctrl <- list(niterEM = 0, msVerbose = TRUE, optimMethod="L-BFGS-B")

# AR(1)
m1 <- get.models(dredge(gamm(Temp ~ s(Month, bs = "cc") + s(Date, bs = 'cr') + Year,
         data = dat, correlation = corARMA(form = ~ 1|Year, p = 1),
         control = ctrl)), subset=1)[[1]]

# AR(2)
m2 <- get.models(dredge(gamm(Temp ~ s(Month, bs = "cc") + s(Date, bs = 'cr') + Year,
         data = dat, correlation = corARMA(form = ~ 1|Year, p = 2),
         control = ctrl)), subset=1)[[1]]

# AR(3)
m3 <- get.models(dredge(gamm(Temp ~ s(Month, bs = "cc") + s(Date, bs = 'cr') + Year,
         data = dat, correlation = corARMA(form = ~ 1|Year, p = 3),
         control = ctrl)), subset = 1)[[1]]


### Select best model to work with based on unselective AIC criteria 
if(AIC(m2$lme) > AIC(m1$lme)){mod = m1}else{mod = m2} 
if(AIC(mod$lme) > AIC(m3$lme)){mod = m3}else{mod = mod}

return(mod$gam)
}

mod2 <- best.mod(dat = test_gam)

Any help would be greatly appreciated.

Thanks, Conor

1
I think the error is get.models calling the dredge model objects because when run as: m1 <- dredge(gamm(Temp ~ s(Month, bs = "cc", k = k.month) + s(Date, bs = 'cr') + Year, data = dat, correlation = corARMA(form = ~ 1|Year, p = 1), control = ctrl)) the function does not crash with this error.Conor Waldock

1 Answers

1
votes

get.models evaluates in model's formula environment, which in gamm is (always?) .GlobalEnv, while it should be function's environment (i.e. sys.frames(sys.nframe())).

So, instead of

get.models(ms, 1)

use

eval(getCall(ms, 1))