下面的示例有两行,每行都有一条线性回归线。要查看每条线性回归线的斜率,我重复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]
答案 0 :(得分:2)
从此处改编:https://community.rstudio.com/t/extract-slopes-by-group-broom-dplyr/2751/2
library(tidyverse);library(broom)
df %>%
group_by(type) %>%
nest() %>%
mutate(model = map(data, ~lm(y ~ x, data = .x) %>%
tidy)) %>%
unnest(model) %>%
filter(term == 'x')
或
df %>%
split(.$type) %>%
map(~lm(y ~ x, data = .x)) %>%
map_df(tidy) %>%
filter(term == 'x')