Search code examples
rdataframelinear-regressionlmbroom

How can I extract slope, intercept and R squared


Here is a toy data.

field <- c('t1','t1','t1', 't2', 't2','t2', 't3', 't3','t3')
predictor <- c(4.2, 5.3, 5.4,6, 7,8.5,9, 10.1,11)
response <- c(5.1, 5.1, 2.4,6.1, 7.7,5.5,1.99, 5.42,2.5)
my_df <- data.frame(field, predictor, response, stringsAsFactors = F)

I would like to group this data based on variable field and fit a regression line using lm() and extract the intercept, slope of the equation, R^2 and other statistical in data frame format.

my_df %>%
group_by(field) %>%
do(glance(lm(predictor ~ response, data = .)))

I tried glance() from broom package. However it does not return the slope and intercept. Any idea how can I fix this?

Thanks,


Solution

  • Another way can be:

    my_df %>%
       group_by(field) %>%
       summarise(model = list(lm(predictor ~ response, data = cur_data())),
                 coef = list(coef(model[[1]])),
                 Rsqrd = summary(model[[1]])$r.sq)%>%
       unnest_wider(coef, names_repair = 'unique')
    
    # A tibble: 3 x 5
      field model  `(Intercept)` response  Rsqrd
      <chr> <list>         <dbl>    <dbl>  <dbl>
    1 t1    <lm>            5.98   -0.241 0.318 
    2 t2    <lm>            9.82   -0.412 0.139 
    3 t3    <lm>            9.69    0.105 0.0379