title: Loop in R to select lowest AIC for a statistical model
body: <p>I want to write a loop to get the lowest AIC value for the following model by changing the degrees of freedom, like <code>df=2</code> in the definition of <code>varknots1</code>. </p>
  
  <p>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. </p>
  
  <p>Could anyone here help me out with this problem?</p>
  
  <pre><code>library(dlnm)
  library(splines)
  
  A = rnorm(500)
  B = rnorm(500)
  C = rnorm(500)
  D = rnorm(500)
  varknots1 &lt;- equalknots(B,fun="bs",df=5,degree=2)
  lagknots1 &lt;- logknots(24, 3)
  cb1 &lt;-crossbasis(B,lag=24,argvar=list(fun="bs",knots=varknots1),arglag=list(knots=lagknots1))   
  
  varknots2 &lt;- equalknots(C,fun="bs",df=5,degree=2)
  lagknots2 &lt;- logknots(24, 3)
  cb2 &lt;- crossbasis(C, lag=24, argvar=list(fun="bs",knots=varknots2), arglag=list(knots=lagknots2))
  
  model&lt;-lm(A~cb1+cb2+D)
  AIC(model)
  </code></pre>