0

How can I get a print-out of the summary for a model fit to each lattice panel?

For example, using the sleepstudy dataste from lme4:

library(lme4)
data(sleepstudy)

I can fit a linear model to all the data and print the summary:

plot(sleepstudy$Days, sleepstudy$Reaction)
model <- lm(formula = Reaction ~ Days,data = sleepstudy)
abline(model, col = "salmon")
summary(model)

enter image description here enter image description here

How can I do print a summary for each lattice panel?

xyplot(Reaction ~ Days | Subject, 
       data = sleepstudy,
       panel = function(x, y, ...) {
         panel.xyplot(x, y, ...)
         fm <- lm(y ~ poly(x, 2))
         panel.lines(x, fitted(fm), col.line="salmon")
       }
       )

enter image description here

a11
  • 3,122
  • 4
  • 27
  • 66
  • For linear regression by group see https://stackoverflow.com/questions/1169539/linear-regression-and-group-by-in-r#1169672 – user20650 Apr 23 '22 at 23:49

1 Answers1

0

You can get the summary functions output either as a list of the values returned or using the print.summary

lapply(split( sleepstudy, sleepstudy$ID), summary) 

If you want the summary.lm result then this succeeds

lapply(split( sleepstudy, sleepstudy$Subject), 
   function(d) {
        summary(
           lm(Reaction ~ poly(Days, 2),data=d) )
               })

  
IRTFM
  • 258,963
  • 21
  • 364
  • 487