1

I know can it's possible to return the p-value of a regression lm by doing this:

# regression model
  fit <- lm(y ~ x)

# two alternative ways to return the p-value
  glance(fit)$p.value 
  summary(fit)$coefficients[,4][2]

However, I need to pipe the result for the purposes of what I want to do. This is what I've tried without success:

lm(y ~ x) %>% glance(.)$p.value 

lm(y ~ x) %>% summary(.)$coefficients[,4][2]

reproducible example

library(magrittr)
library(broom)

x <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
y <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
rafa.pereira
  • 13,251
  • 6
  • 71
  • 109

2 Answers2

2

It is recommended here that you avoid using the $ operator to extract coefficients. To be more explicit in what you're looking for, and more robust to library changes, try this instead:

coef(summary(fit))["x","Pr(>|t|)"]

But that makes your piping tough. You could try this, if it works for your purposes:

getp <- function(coefs) { return (coefs["x","Pr(>|t|)"]) }
lm(y ~ x) %>% summary %>% coef %>% getp

That works for me, and you could even add arguments for which column you'd like to extract in your one-line function.

Community
  • 1
  • 1
mightypile
  • 7,589
  • 3
  • 37
  • 42
0

Try this:

library(magrittr)

{ y ~ x } %>% lm %>% summary %>% coef %>% .["x", "Pr(>|t|)"]
## [1] 0.18351

or

{ y ~ x } %>% lm %>% summary %>% coef %>% `[`("x", "Pr(>|t|)")
## [1] 0.18351

or use 2 and 4 in place of "x" and "Pr(>|t|)" in either of the above.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341