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

67 Views Asked by At

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.

2

There are 2 best solutions below

2
Jilber Urbina On BEST ANSWER

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 
0
G. Grothendieck On

We can use broom like this:

library(broom)
model <- lm(y1 ~ x1 + x2 + x3, anscombe)

fmt <- "Multiple R-squared: = %f, Adjusted R-squared: %f, F-statistic: %f on %d and %d dof, p-value < %f"
with(glance(model),
  sprintf(fmt, r.squared, adj.r.squared, statistic, df, df.residual, p.value)
)

## [1] "Multiple R-squared: = 0.666542, Adjusted R-squared: 0.629492, F-statistic: 17.989943 on 1 and 9 dof, p-value < 0.002170"