7
votes

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.

2
here is it on flickr: flickr.com/photos/132350438@N04?Ravi
thanks in advance..RV.Ravi

2 Answers

5
votes

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
3
votes

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))