Search code examples
rlme4tidymodels

How to extract random intercepts from mixed effects Tidymodels


I am trying to extract random intercepts from tidymodels using lme4 and multilevelmod. I able to do this using lme4 below:

Using R and lme4:

library("tidyverse")
library("lme4")

# set up model
mod <- lmer(Reaction ~ Days + (1|Subject),data=sleepstudy)

# create expanded df
expanded_df <- with(sleepstudy,
                    data.frame(
                      expand.grid(Subject=levels(Subject),
                                  Days=seq(min(Days),max(Days),length=51))))

# create predicted df with **random intercepts**
predicted_df <- data.frame(expanded_df,resp=predict(mod,newdata=expanded_df))

predicted_df 

# plot intercepts
ggplot(predicted_df,aes(x=Days,y=resp,colour=Subject))+
       geom_line() 

enter image description here

Using tidymodels:

# example from
# https://github.com/tidymodels/multilevelmod
library("multilevelmod")
library("tidymodels")
library("tidyverse")
library("lme4")
#> Loading required package: parsnip
data(sleepstudy, package = "lme4")


# set engine to lme4
mixed_model_spec <- linear_reg() %>% set_engine("lmer")


# create model
mixed_model_fit_tidy <- 
  mixed_model_spec %>% 
  fit(Reaction ~ Days + (1 | Subject), data = sleepstudy)


expanded_df_tidy <- with(sleepstudy,
                    data.frame(
                      expand.grid(Subject=levels(Subject),
                                  Days=seq(min(Days),max(Days),length=51))))



predicted_df_tidy <- data.frame(expanded_df_tidy,resp=predict(mixed_model_fit_tidy,new_data=expanded_df_tidy))


ggplot(predicted_df_tidy,aes(x=Days,y=.pred,colour=Subject))+
       geom_line()

enter image description here

Using the predict() function seems to gives only the fixed effect predictions.

Is there a way to extract the random intercepts from tidymodels and multilevelmod? I know the package is still in development so it might not be possible at this stage.


Solution

  • I think you can work around this as follows:

    predicted_df_tidy <- mutate(expanded_df_tidy,
           .pred = predict(mixed_model_fit_tidy,
                           new_data=expanded_df_tidy, 
                           type = "raw", opts=list(re.form=NULL)))
    

    prediction plot with random intercepts

    If you actually want the random intercepts (only) I guess you could predicted_df_tidy %>% filter(Days==0)

    PS If you want to be more 'tidy' about this I think you can use purrr::cross_df() in place of expand.grid and pipe the results directly to mutate() ...