7

我正在尝试从 qplot 中提取 500 个变量的截距和斜率。我正在使用的代码:

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

有人可以帮我提取每条回归线(500 条线/变量)的截距和斜率,如附图中所示。

4

2 回答 2

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
于 2015-05-11T09:17:30.513 回答
3

lmList使用该函数如何计算跨多个组的线性回归?

library("nlme")
coef(lmList(nd~gd|ENT , data = test))
于 2015-05-11T11:08:13.790 回答