grautur - 1 month ago 4x

R Question

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)

summary(fit)

I know that

`summary(fit)`

Answer

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
return(p)
}
> 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.

Source (Stackoverflow)

Comments