title: Random effects modeling using mgcv and using lmer. Basically identical fits but VERY different likelihoods and DF. Which to use for testing?
body: <p>I am aware that there is a duality between random effects and smooth curve estimation. <a href="https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/random.effects.html" rel="nofollow">At this link</a>, Simon Wood describes how to specify random effects using mgcv. Of particular note is the following passage: </p>
  
  <blockquote>
    <p>For example if g is a factor then s(g,bs="re") produces a random coefficient for each level of g, with the radndom coefficients all modelled as i.i.d. normal.</p>
  </blockquote>
  
  <p>After a quick simulation, I can see this is correct, and that the model fits are almost identical. However, the likelihoods and degrees of freedom are VERY different. Can anyone explain the difference? Which one should be used for testing? </p>
  
  <pre><code>library(mgcv)
  library(lme4)
  set.seed(1)
  x &lt;- rnorm(1000) 
  ID &lt;- rep(1:200,each=5)
  y &lt;- x 
  for(i in 1:200) y[which(ID==i)] &lt;- y[which(ID==i)] + rnorm(1)
  y &lt;- y + rnorm(1000)
  ID &lt;- as.factor(ID)
  
  # gam (mgcv)
  m &lt;- gam(y ~ x + s(ID,bs="re"))
  gam.vcomp(m)
  coef(m)[1:2]
  logLik(m)
  
  # lmer
  m2 &lt;- lmer(y ~ x + (1|ID))
  sqrt(VarCorr(m2)$ID[1])
  summary(m2)$coef[,1]
  logLik(m2)
  
  mean( abs( fitted(m)-fitted(m2) ) )
  </code></pre>
  
  <p>Full disclosure: I encountered this problem because I want to fit a GAM that also includes random effects (repeated measures), but need to know if I can trust likelihood-based tests under those models. </p>