I would do that like this
library(tidyverse)
mtcars2 <- select(mtcars, gear, mpg)
lm18k <- lm(hp ~ splines::bs(mpg, df = 2, degree = 1, knots = 18), mtcars)
mtcars2$lm18k <- predict(lm18k, newdata = mtcars)
lm19k <- lm(hp ~ splines::bs(mpg, df = 2, degree = 1, knots = 19), mtcars)
mtcars2$lm19k <- predict(lm19k, newdata = mtcars)
lm20k <- lm(hp ~ splines::bs(mpg, df = 2, degree = 1, knots = 20), mtcars)
mtcars2$lm20k <- predict(lm20k, newdata = mtcars)
mtcars3 <- pivot_longer(mtcars2,
cols = (lm18k:lm20k)
) %>%
mutate(keepme = case_when(
name == "lm18k" & gear == 3 ~ TRUE,
name == "lm19k" & gear == 4 ~ TRUE,
name == "lm20k" & gear == 5 ~ TRUE,
TRUE ~ FALSE
)) %>%
filter(keepme)
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point() +
geom_smooth(
data = mtcars3,
method = lm, mapping = aes(y = value)
) +
facet_wrap(~gear)