title: Random Effects in Longitudinal Multilevel Imputation Models Using MICE
body: <p>I am trying to impute data in dataset with a longitudinal design. There are two predictors (experimental group, and time) and one outcome variable (score). The clustering variable is id.</p>
  <p>Here is the toy data</p>
  <pre><code>set.seed(345)
  A0 &lt;- rnorm(4,2,.5)
  B0 &lt;- rnorm(4,2+3,.5)
  A1 &lt;- rnorm(4,6,.5)
  B1 &lt;- rnorm(4,6+2,.5)
  A2 &lt;- rnorm(4,10,.5)
  B2 &lt;- rnorm(4,10+1,.5)
  A3 &lt;- rnorm(4,14,.5)
  B3 &lt;- rnorm(4,14+0,.5)
  score &lt;- c(A0,B0,A1,B1,A2,B2,A3,B3)
  id &lt;- rep(1:8,times = 4, length = 32)
  time &lt;- rep(0:3, each = 8, length = 32)
  group &lt;- rep(c(&quot;A&quot;,&quot;B&quot;), times =2, each = 4, length = 32)
  df &lt;- data.frame(id = id, group = group, time = time,  score = score)
  
  # plots
  (ggplot(df, aes(x = time, y = score, group = group)) + 
      stat_summary(fun.y = &quot;mean&quot;, geom = &quot;line&quot;, aes(linetype = group)) +
      stat_summary(fun.y = &quot;mean&quot;, geom = &quot;point&quot;, aes(shape = group), size = 3) +
      coord_cartesian(ylim = c(0,18)))
  
  # now place some NAs
  df[sample(1:nrow(df), 10, replace = F),&quot;score&quot;] &lt;- NA
  
  df
  </code></pre>
  <p>If I understand <a href="https://stackoverflow.com/questions/38100892/imputation-using-mice-with-clustered-data">this post</a> correctly, in the predictor matrix I should specify the <code>id</code> clustering variable with a <code>-2</code> and the two fixed predictors <code>time</code> and <code>group</code> with a <code>1</code>. Like so</p>
  <pre><code>library(mice)
  
  (ini &lt;- mice(df, maxit=0))
  (pred &lt;- ini$predictorMatrix)
  (pred[&quot;score&quot;,] &lt;- c(-2, 1, 1, 0))
  (imp &lt;- mice(df, 
              method = c(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;2l.pan&quot;),
              pred = pred, 
              maxit = 1, 
              seed = 71152))
  </code></pre>
  <p>What i would like to know is:</p>
  <ol>
  <li>Is this a longitudinal random intercepts imputation model? Specifying the id variable as <code>-2</code> designates it as a 'class' variable, but in <a href="https://research.utwente.nl/en/publications/mice-multivariate-imputation-by-chained-equations-in-r" rel="nofollow noreferrer">this mice primer</a> it suggests that for multilevel models you should create a variable of all <code>1</code>'s in the dataframe as a constant, which is then specified as the random intercept via <code>2</code> in the predictor matrix. However, this is based on the <code>2l.norm</code> function rather than the <code>2l.pan</code> function, so I am not really sure where I am here. Does the <code>2l.pan</code> function not require this column, or the specification of random effects?</li>
  <li>Is there any way to specify a longitudinal random-slopes model, and, if so, how?</li>
  </ol>