I want to write a loop to get the lowest AIC value for the following model by changing the degrees of freedom, like df=2
in the definition of varknots1
.
I just use random data here since I don't know how to upload my data. I am trying to learn to write loops my self, however, I never succeeded to make this one at present.
Could anyone here help me out with this problem?
library(dlnm)
library(splines)
A = rnorm(500)
B = rnorm(500)
C = rnorm(500)
D = rnorm(500)
varknots1 <- equalknots(B,fun="bs",df=5,degree=2)
lagknots1 <- logknots(24, 3)
cb1 <-crossbasis(B,lag=24,argvar=list(fun="bs",knots=varknots1),arglag=list(knots=lagknots1))
varknots2 <- equalknots(C,fun="bs",df=5,degree=2)
lagknots2 <- logknots(24, 3)
cb2 <- crossbasis(C, lag=24, argvar=list(fun="bs",knots=varknots2), arglag=list(knots=lagknots2))
model<-lm(A~cb1+cb2+D)
AIC(model)
aic<-rep(NA,8)
for(i in 1:8){
varknots1 <- equalknots(B,fun="bs",df=(i+2),degree=2)
lagknots1 <- logknots(24, 3)
cb1 <-crossbasis(B,lag=24,argvar=list(fun="bs",knots=varknots1),arglag=list(knots=lagknots1))
varknots2 <- equalknots(C,fun="bs",df=(i+2),degree=2)
lagknots2 <- logknots(24, 3)
cb2 <- crossbasis(C, lag=24, argvar=list(fun="bs",knots=varknots2), arglag=list(knots=lagknots2))
aic[i]<-AIC(lm(A~cb1+cb2+D))
}