3

I'm trying to build a series of linear models for a set of Standard Curves.

Currently this code is working to produce my desired outputs (Intercept and Slope of each Linear Model):

slopes <- STANDARDS %>% group_by(plate, col, row, conc_ug_mL) %>% do(
    #model = lm(value ~ variable, data = .),
    intercept = coef(lm(value ~ variable, data = .))[1],
    slope = coef(lm(value ~ variable, data = .))[2])

But I had to comment the model line out and call lm twice. I would really like to make it like this:

slopes2 <- STANDARDS %>% group_by(plate, col, row, conc_ug_mL) %>% do(
    model = lm(value ~ variable, data = .),
    intercept = coef(.$model)[1],
    slope = coef(.$model)[2])

The second block of code does not raise an error but return NULL for both Intercept and Slope. I think my problem is not understanding the reference structure within dplyr::do.

But am just learning dplyr and not sure of how to do this. Thanks.

Nate
  • 10,361
  • 3
  • 33
  • 40
  • Welcome to SO. Your question is not reproducible, please see [this FAQ](http://stackoverflow.com/q/5963269/2572423) for more information. In addition, this [blog post](http://blog.rstudio.org/2016/02/02/tidyr-0-4-0/) and the [broom](https://github.com/dgrtwo/broom) package may prove helpful. – JasonAizkalns Feb 03 '16 at 16:00
  • the package [broom](https://cran.r-project.org/web/packages/broom/vignettes/broom_and_dplyr.html) might be useful here. – erc Feb 03 '16 at 16:00
  • Thanks @JasonAizkalns. I will make sure my future posts comply with the community's reproducibility guide lines. I appreciate the broom package recommendation, I will start using that to helpfully format my dplyr outputs! – Nate Feb 04 '16 at 18:04
  • Thank you for the broom recommendation too! @beetroot – Nate Feb 04 '16 at 18:04

1 Answers1

2

We don't need the .$model. Using a reproducible example

 data(mtcars)
 mtcars %>%
   group_by(cyl) %>% 
   do({model = lm(wt~gear, data=.)
   data.frame(intercept= coef(model)[1], slope=coef(model)[2])})
 #    cyl intercept      slope
 # (dbl)     (dbl)      (dbl)
 #1     4  3.829406 -0.3773438
 #2     6  4.180750 -0.2757500
 #3     8  5.205208 -0.3670417
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for your solution, and apologies for not making my example reproducible. Could you explain the significance of the ' { ' ? When I tried replacing the ' { ' with ' ( ' an error was returned. Is ' { ' just defining a unnamed function? – Nate Feb 04 '16 at 18:20
  • @NathanDay It is to separate multiple lines. – akrun Feb 04 '16 at 18:31