grautur grautur - 1 month ago 4x
R Question

pull out p-values and r-squared from a linear regression

How do you pull out the p-value (for the significance of the coefficient of the single explanatory variable being non-zero) and R-squared value from a simple linear regression model? For example...

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)

I know that
displays the p-value and R-squared value, but I want to be able to stick these into other variables.


You can return the r-squared value directly from the summary object summary(fit)$r.squared. See names(summary(fit)) for a list of all the items you can extract directly.

This blog post outlines a function to return the p-value:

lmp <- function (modelobject) {
    if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
    f <- summary(modelobject)$fstatistic
    p <- pf(f[1],f[2],f[3],lower.tail=F)
    attributes(p) <- NULL

> lmp(fit)
[1] 1.622665e-05

Alternatively, you can grab the p-value from the anova(fit) object in a similar fashion to the summary object above.