Search code examples
rr-s4

How to extract predicted marginal means from an lsmobj


The lsmeans package makes it easy to get predicted marginal means, so long as you do it manually. I want to automate this in a function that only uses the predicted means.

Here is an example from the vignette:

library("lsmeans")
data(oranges)
oranges.lm1 <- lm(sales1 ~ price1 + price2 + day + store, data = oranges)
lsmeans(oranges.lm1, "day")
# day    lsmean       SE df  lower.CL  upper.CL
# 1    5.564415 1.768083 23  1.906856  9.221974
# 2    6.494807 1.728959 23  2.918183 10.071430
# 3   13.664571 1.751505 23 10.041308 17.287835
# 4    8.742289 1.733920 23  5.155403 12.329175
# 5   15.441803 1.785809 23 11.747576 19.136029
# 6   11.394782 1.766726 23  7.740031 15.049533

What I would like is something like this:

lsmeans(oranges.lm1, "day")[,2]
# 5.564415 6.494807 13.664571 8.742289 15.441803 11.394782 

But that does not work (it prints the same output as above). I don't know if this is because the result (an lsmobj object) is an S4 object. How can I extract just the lsmean column as a vector?


Solution

  • The proper way, as pointed out by @rvl, would be to use predict

    predict(lsmeans(oranges.lm1, "day"))
    

    A less efficient alternative would be summary, which will call lsmeans:::summary.ref.grid in turn

    summary(lsmeans(oranges.lm1, "day"))[,2]
    # [1]  5.564415  6.494807 13.664571  8.742289 15.441803 11.394782