简体   繁体   中英

mgcv::gamm() and MuMIn::dredge() errors

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

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

So, instead of

get.models(ms, 1)

use

eval(getCall(ms, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM