Search code examples
rlmsummarytail

How to return the last two lines of summary output from a linear model in R?


After finding a regression prediction in lm I want to return only last two lines of the summary. What would be the best function to use?

my_model_lm(y ~ x1 + x2 + x3, data = [data])
summary_result <- summary(my_model)

I want to return only: Multiple R-squared: [value], Adjusted R-squared: [value] F-statistic: [value] on [value] and [value] DF, p-value: < [value]

I tried the tail() function, cat() function, summary(my_model$)r.squared at some basic level. Was not able to return the desirable output.


Solution

  • You can capture.output then select with tail and print with cat

    cat(tail(capture.output(summary_result), 3))
    

    A complete example:

    > my_model <- lm(mpg ~ hp + wt, data=mtcars)
    > summary_result <- summary(my_model)
    > cat(tail(capture.output(summary_result), 3))
    Multiple R-squared:  0.8268,    Adjusted R-squared:  0.8148  F-statistic: 69.21 on 2 and 29 DF,  p-value: 9.109e-12 
    

    If you want to assign the output to a variable, then you can do:

    >  output <- tail(capture.output(summary_result), 3)
    

    Afterwards you can print it using cat

    > cat(output) 
    Multiple R-squared:  0.8268,    Adjusted R-squared:  0.8148  F-statistic: 69.21 on 2 and 29 DF,  p-value: 9.109e-12