我一直在尝试使用函数中的包mgcv
来适应多个GAM,并通过模型选择过程粗略地选择最合适的模型。但是我的函数运行第一个模型,然后似乎再次无法识别输入数据dat
。
我收到错误
is.data.frame(data)出错:找不到对象'dat'。
我认为这是一个范围问题,我看了here和here寻求帮助,但无法弄明白。
代码和数据如下(希望可重复): 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)
非常感谢任何帮助。
谢谢, 康纳
答案 0 :(得分:1)
get.models
在模型formula
环境中进行评估,gamm
中的.GlobalEnv
(总是吗?)sys.frames(sys.nframe())
,虽然它应该是功能的环境(即
get.models(ms, 1)
)。
所以,而不是
eval(getCall(ms, 1))
使用
{{1}}