7

I am trying to extract intercepts and slopes for 500 variables from a qplot. The code I am using:

qplot(gd, nd, data = test, colour = factor(ENT)) + 
  geom_smooth(method = "lm", se = FALSE)

Could someone help me extract the intercept and slope for each regression line (500 lines/variables) as plotted in the attached figure.

Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
Ravi
  • 81
  • 1
  • 4

2 Answers2

5

ggplot will draw the graph, but you extract the coefficients (Intercepts and Slopes) from the lm() objects. One way to do the latter is to use dplyr's group_by() and do() functions. See ?do

I'm using the mtcars data frame here.

library(ggplot2)
library(dplyr)

ggplot(mtcars, aes(mpg, disp, colour = factor(cyl))) +
   geom_point() +
   geom_smooth(method = "lm", se = FALSE)

mtcars %>% 
    group_by(cyl) %>% 
    do({
      mod = lm(disp ~ mpg, data = .)
      data.frame(Intercept = coef(mod)[1],
                 Slope = coef(mod)[2])
    })


Source: local data frame [3 x 3]
Groups: cyl

  cyl Intercept      Slope
1   4  233.0674  -4.797961
2   6  125.1225   2.947487
3   8  560.8703 -13.759624
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
  • Hi all, I am using some logistic model where I can extract slope, and inflection point. But I would like to extract y-resonses at a certain position on the logistic fit curve. For example, in the figure attached. – Ravi Jun 05 '15 at 21:57
  • @Ravi, you should ask a new question. Also, figures don't attach to comments. – Sandy Muspratt Jun 06 '15 at 05:08
  • Hi Sandy..Yes I have asked this question separately here: http://stackoverflow.com/questions/30676509/extracting-defined-response-points-in-logistic-fits – Ravi Jun 09 '15 at 02:58
3

How about using the lmList function, which is designed for computing linear regressions across multiple groups?

library("nlme")
coef(lmList(nd~gd|ENT , data = test))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453