I don't understand the details of your model, but if you are looking to minimize (or maximize) edf
for models fitted with different sp
, optim
will do the job. First, create a function that returns just the edf
given different values of sp
.
edf.by.sp<-function(sp) {
model <-gam(resp ~ s(time,bs='cr',k=6*15, fx=F)+ s(temp,k=6, bs='cr') +
as.factor(dow),
family=quasipoisson,
na.action=na.omit,
data=df1,
sp= c(sp, 17.23785) # Not sure if this quite right.
)
abs(summary(model)$s.table['s(time)','edf']-60) # Subtract 60 and flip sign so 60 is lowest.
}
Now, you can just run optim
to minimize edf
:
# You could pick any reasonable starting sp value.
# Many optimization methods are available, but in your case
# they work equally well.
best<-optim(12,edf.by.sp,method='BFGS')$par
best
# 16.82708
and, subbing back in, you get nearly 0 (exactly 60 before transforming) when plugging in the function:
edf.by.sp(best) # 2.229869e-06