Error: Problem with `mutate()` column (...) must be size 15 or 1, not 17192

Viewed 7057

I am currently trying to plot a the outcome of an lme4::lmer function, following this tutorial. I've tried the code in the tutorial, and it works as intended. In the tutorial a column pred_dist is added to the dataset for the fitted function before plotting. When I try this with my own data, I get the following error:

Error: Problem with `mutate()` column `pred_dist`.
ℹ `pred_dist = fitted(model0)`.
ℹ `pred_dist` must be size 15 or 1, not 17192.
ℹ The error occurred in group 1: sgroup = 578, group = 1.

Sample data

My code:

# Loaded libraries
library(dplyr)
library(ggplot2)
library(lme4)
library(lmerTest)
library(lattice)

# My lmer model. myData is fairly 
model0 <- lmer(outcome ~ (1|group), data=myData, REML = FALSE)
summary(model0)

myData %>% 
    # save predicted values
    mutate(pred_dist = fitted(model0)) 

What I am trying to understand is: What is causing this error message, and how do I resolve it?


Update:

As per bouncyball's comment I added ungroup() before mutate(). This worked for my initial model, but not the subsequent. I tried the following:

> model1 <- lmer(outcome ~ predictor + (1|group), myData, REML=FALSE) 

> plotVar$pred_dist = fitted(model1). 

Error: Assigned data 'value' must be compatible with existing data. 
✖ Existing data has 17192 rows. 
✖ Assigned data has 16794 rows. 
ℹ Only vectors of size 1 are recycled.

> plotVar %>% ungroup(.) 
          %>% mutate(pred_dist = fitted(model1)) 

Error: Problem with 'mutate()' column 'pred_dist'. 
ℹ 'pred_dist = fitted(model1)'. 
ℹ 'pred_dist' must be size 17192 or 1, not 16794.
1 Answers

My very strong guess is that there are two different things going on here: (1) grouping (2) NA values.

Let's make up an example that is both grouped and contains NA values:

library(dplyr)
library(lme4)
ss <- sleepstudy |> group_by(Subject)
ss$Days[1:5] <- NA

m0 <- lmer(Reaction ~ Days + (Days | Subject), ss)

Try the original code:

ss |> mutate(pred = fitted(m0))

ℹ pred must be size 10 or 1, not 175.
ℹ The error occurred in group 1: Subject = 308.

Try with ungroup():

ss |> ungroup() |> mutate(pred = fitted(m0))

ℹ pred = fitted(m0).
ℹ pred must be size 180 or 1, not 175.

We still get an error, but note that the sizes are different.

Now update the model using na.action = na.exclude (this could have been done in the first model, or can be done by setting options(na.action = "na.exclude"):

m1 <- update(m0, na.action = na.exclude)
ss |> ungroup() |> mutate(pred = fitted(m1))
Related