Search code examples
rregressionmagrittr

Pipe `%>%` the results of a regression `lm`and return one of the attributes


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)

Solution

  • 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.