简体   繁体   中英

Efficient way to extract coefficients from many linear regression lines

The example below has two lines and a linear regression line for each. To see the slope of each linear regression line I repeat lm twice. Suppose instead of having two types, "A" and "B", I have many. What is the efficient way to create a vector of slopes for all of my linear regression lines?

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]

Adapted from here: 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')

or

df %>% 
  split(.$type) %>% 
  map(~lm(y ~ x, data = .x)) %>% 
  map_df(tidy) %>%
  filter(term == 'x')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM