Skip to content

Instantly share code, notes, and snippets.

@juanchiem
Created December 21, 2022 20:21
Show Gist options
  • Save juanchiem/04e806464eb61bba0173a397835a8506 to your computer and use it in GitHub Desktop.
Save juanchiem/04e806464eb61bba0173a397835a8506 to your computer and use it in GitHub Desktop.
library(segmented)
library(tidyverse)
#view DataFrame
df <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
y=c(2, 4, 5, 6, 8, 10, 12, 13, 15, 19, 24, 28, 31, 34, 39, 44))
df2 <- data.frame(x=c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)+2,
y=c(4, 5, 6, 8, 10, 12, 13, 15, 19, 24, 28, 31, 34, 39))
fit <- lm(y ~ x, data=df)
segmented.fit <- segmented(fit, seg.Z = ~x, psi=9)
preds1 <- data.frame(x = seq(min(df$x), max(df$x)),
y = fitted(segmented.fit))
fit2 <- lm(y ~ x, data=df2)
segmented.fit2 <- segmented(fit2, seg.Z = ~x, psi=9)
preds2 <- data.frame(x = seq(min(df2$x), max(df2$x)),
y = fitted(segmented.fit2))
preds1 %>%
ggplot() +
geom_line(aes(x,y, col="hib A"))+
geom_point(aes(x,y), col="red")+
geom_line(data = preds2, aes(x,y, col="hib B"), )+
geom_point(data = preds2, aes(x,y), col="green") +
scale_colour_manual("Hibrido", values = c("red", "green"))
@juanchiem
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment