R-从许多线性回归线中提取系数的有效方法



下面的示例都有两条线和一个线性回归线。要查看每个线性回归线的斜率,我两次重复lm。假设我有很多类型的" A"one_answers" 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]

从这里改编:https://community.rstudio.com/t/extract-slopes-by-group-broom-broom-dplyr-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')

最新更新