Search code examples
rsummarylm

How to obtain just particular lines of summary on lm object


This problem comes from easier problem which I managed to solve myself. So here is my original question.

In my data I have lots of categories, but i'm not interested in estimating coefficients for all of them, I just want to test the hypothesis, that there is no difference in categories. And calling summary on my object produces most information that I don't need for my report.

set.seed(42)
dat <- data.frame(cat=factor(sample(1:10, 100, replace=T)), y=rnorm(100))
l1 <- lm(y~cat-1, data=dat)
summary(l1)

How do I extract only the last line from call to summary(l1)?

In this particular case I can just used anova function

anova(l1)

and got only the info that I needed, just in different formatting than summary(l1) produces.

What if I have some kind of a summary on an object and I want to extract just particular part of summary(object) how do I do that? For example, how do I get R to print only the line of call summary(l1)?

p.s. I am aware of summary(l1)$fstatistic.


Solution

  • OK, I'm in a literal mood, but using capture.output will return the character representation of an evaluated object. So for example, using your l1 object:

    l1Out <- capture.output(summary(l1))
    grep("^F-st", l1Out, value = TRUE)
    # [1] "F-statistic: 1.323 on 10 and 90 DF,  p-value: 0.2303 "
    

    Note, however, that this is not the last line of output:

    tail(l1Out, 1)
    # [1] ""
    

    And for many components of the summary object, there are better ways to extract information, such as @seancarmody wrote

    l1$call
    # lm(formula = y ~ cat - 1, data = dat)