如何计算R中多个图上不同线性回归线的斜率

How to calculate the slopes of different linear regression lines on multiple plots in R

我现在使用 facet 通过不同的 i 值绘制多个分布图,并找到每条回归线的 slope在相应的地块上。

我的数据集格式如下,这里是整个文件的link(https://drive.google.com/file/d/0B_biBFUMCaA2SGlFc2I0OTd3djA/view?usp=sharing)

我使用以下 R 代码绘制多个图:

bound = read.csv("strength_distribution")
sp <- ggplot(bound, aes(x,y)) + geom_point(shape=1)+ 
scale_y_log10()+ scale_x_log10()+ggtitle("Node Strength Distribution")+
      theme(plot.title= element_text(size =16, face ="bold", 
              lineheight = 8, vjust=1), aspect.ratio=1)+
      stat_smooth(method="lm", se = FALSE) + scale_shape_identity()
sp + facet_wrap( ~ i, ncol=3, scales = "free_x" )
ggplotly()

然后我得到以下情节:

我发现有多种方法可以计算一个图中的回归线的斜率,但不知道如何编写一个函数来计算多个图中的多个回归线的斜率。有谁知道如何处理这种情况?谢谢

rawr 在评论中为您提供了完美的答案,但如果您有兴趣...

如果您对数据的子集做相当复杂的事情,那么非常值得检查一下 R 中的 group_by() %>% nest() %>% map() 工作流程。我将用一个简单的例子来演示:

library(dplyr)
library(tidyr)
library(purrr)
data(iris)

这些是您要应用于子集的一些函数。

doModel <- function(dat) lm(Sepal.Length ~ Sepal.Width, dat)
getSlope <- function(mod) coef(mod)[2]

您可以按如下方式应用它们。

models <- iris %>% 
  group_by(Species) %>%
  nest %>%
  mutate(model = map(data, doModel)) %>% 
  mutate(slope = map(model, getCoef))

models$slope

您在 data.frame 中用 nest() 创建了一些 data.frame。然后你使用 map() 对每个子 data.frame 应用一个函数。如果您对每个子集都有非常细微的事情要做,那么这种工作流程会非常有用。

强烈推荐观看hadleys talk on this。如果你愿意,很乐意提供更多帮助...