【发布时间】:2019-05-18 02:56:00
【问题描述】:
下面的示例有两条线和一条线性回归线。要查看每条线性回归线的斜率,我重复 lm 两次。假设我有很多类型,而不是“A”和“B”两种类型。为我的所有线性回归线创建斜率向量的有效方法是什么?
library(tidyverse)
df <- tibble(
x = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6),
y = c(1, 3, 2, 4, 1, 4, 2, 5, 3, 7, 5, 10),
type = c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B")
)
ggplot(df, aes(x = x, y = y)) +
geom_line(aes(colour = type), size = 4) +
scale_x_continuous(breaks = 0:6, limits = c(0,6)) +
scale_y_continuous(breaks = seq(0, 10, 0.5)) +
geom_smooth(data = df, aes(x = x, y = y, group = type), method = "lm", se = FALSE, size = 0.5,
n = 2, col = rep(c("darkgoldenrod1", "blue"), each = 2)) +
scale_color_manual(values = c("A" = "dark red", "B" = "dark blue")) +
theme_minimal()
# Fit lm model
linearModA <- lm(y ~ x, data = filter(df, type == "A"))
# Extract slope
linearModA[[1]][2]
linearModB <- lm(y ~ x, data = filter(df, type == "B"))
linearModB[[1]][2]
【问题讨论】:
-
使用
lapply和lm.fit。lm.fit也有一个coef方法。