Reputation: 21
I want to run different gam models with the combination of various k values (k=i,k=j,k=l,k=m,k=n and range for i=4,5,6,7,8 and same for j,l,m,n) at a time, using R studio. Actually, I need AIC of each model for various k's. I have started with this code:
library(mgcv)
u<-c(4:8)
v<-c(4:8)
w<-c(4:8)
x<-c(4:8)
y<-c(4:8)
n<-1
aic<-0
kt<-""
for(i in u){for(j in v){for (l in w){for(m in x){for(n in y)
{fit<-gam(dat$y~dat$x1+s(pc1,bs="cr",k=i)
+s(pc2,bs="cr",k=j)+s(pc3,bs="cr",k=l)
+s(pc4,bs="cr",k=m)+s(pc5,bs="cr",k=n)
+as.factor(dat$x2),data=dat,family=poisson,method="REML")
aic[n]<-AIC(fit)
kt[n]<-paste("A",i,"B",j,"C",l,"D",m,"E",n)
n<-n+1}}}}
result<-data.frame(aic,kt)
result
And got this output
aic kt
1 0.000
2 NA <NA>
3 NA <NA>
4 8363.725 A 8 B 8 C 8 D 8 E 4
5 8354.917 A 8 B 8 C 8 D 8 E 5
6 8355.699 A 8 B 8 C 8 D 8 E 6
7 8356.166 A 8 B 8 C 8 D 8 E 7
8 8356.281 A 8 B 8 C 8 D 8 E 8
I think I did some mistake here with the code. Can anybody please help me?
Upvotes: 1
Views: 501
Reputation: 1502
I don't have your data and have not run this solution to see if it works. You use the variable n for two different things. Here, I change the name of the main counter from n to nn.
library(mgcv)
u<-c(4:8)
v<-c(4:8)
w<-c(4:8)
x<-c(4:8)
y<-c(4:8)
nn<-1
aic<-0
kt<-""
for(i in u){for(j in v){for (l in w){for(m in x){for(n in y)
{fit<-gam(dat$y~dat$x1+s(pc1,bs="cr",k=i)
+s(pc2,bs="cr",k=j)+s(pc3,bs="cr",k=l)
+s(pc4,bs="cr",k=m)+s(pc5,bs="cr",k=n)
+as.factor(dat$x2),data=dat,family=poisson,method="REML")
aic[nn]<-AIC(fit)
kt[nn]<-paste("A",i,"B",j,"C",l,"D",m,"E",n)
nn<-nn+1}}}}
result<-data.frame(aic,kt)
result
Upvotes: 2