Search code examples
rlmemmeans

fitted values for every case in dataset with emmeans


I'm trying to get disp predictions for each observation in mtcars with emmeans. I can get average disp predictions with:

library(emmeans)
mod <- lm(mpg ~ disp + hp, data = mtcars)
emm <- emmeans(mod, "disp", at=list(disp=c(130,135,140)))

However, is it possible to get the fitted values for every single case in the dataset, similar to what I get with predict(mod)?

EDIT: Ben Bolker suggested this:

nd <- expand.grid(hp = unique(mtcars$hp), disp = 130)
mean(predict(mod, newdata = nd))
23.20037

However, this doesn't match the average I get in emmeans:

emmeans(mod, "disp", at=list(disp=130))

disp emmean    SE df lower.CL upper.CL
  130   23.1 0.928 29     21.2       25

Solution

  • How about

    nd <- expand.grid(hp = unique(mtcars$hp), disp = c(130,135,140))
    predict(mod, newdata = nd)
    

    ?

    (or skip the unique() if you really want predictions for every observation even if they have non-unique hp ...)

    If you want a predicted frame whose mean matches emmeans, you do want to skip the unique(). If you only want to consider a single value of disp, you don't need the expand.grid:

    nd <- data.frame(hp = mtcars$hp, disp = 130)
    mean(predict(mod, newdata = nd))
    ## [1] 23.14716
    

    Comparing with emmeans (convert to data frame so we can see full resolution)

    as.data.frame(emmeans(mod, "disp", at=list(disp=130)))
     disp   emmean        SE df lower.CL upper.CL
      130 23.14716 0.9283063 29 21.24856 25.04576