Last active
December 14, 2018 11:11
-
-
Save padpadpadpad/85377552b9a1bb5ff59587298c441694 to your computer and use it in GitHub Desktop.
forcing a segmented regression through the origin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # forcing a segmented regression through the origin. | |
| # load packages | |
| library(segmented) | |
| # make data | |
| d <- data.frame(x = c(3, 13, 18, 19, 19, 26, 26, 33, 40, 49, 51, 53, 67, 70, 88 | |
| ), | |
| y = c(3.56211608128595, 10.5214485148819, 3.66063708049802, 6.11000808621074, | |
| 5.51520423804034, 7.73043895812661, 7.90691392857039, 6.59626527933846, | |
| 10.4413913666936, 8.71673928545967, 9.93374157928462, 1.214860139929, | |
| 3.32428882257746, 2.65223361387063, 3.25440939462105)) | |
| # fit normal linear regression and segmented regression | |
| lm1 <- lm(y ~ x, d) | |
| lm2 <- lm(y ~ 0 + x, d) | |
| seg_lm <- segmented(lm1, ~ x) | |
| seg_lm2 <- segmented(lm2, ~ x) | |
| slope(seg_lm) | |
| # make predictions | |
| preds1 <- data.frame(x = data.frame(x=0:100), preds = predict(seg_lm, newdata = data.frame(x=0:100))) | |
| preds2 <- data.frame(x = data.frame(x=0:100), preds = predict(seg_lm2, newdata = data.frame(x=0:100))) | |
| # plot segmented fit | |
| plot(seg_lm, res = TRUE, xlim = c(0,95), ylim = c(0,11)) | |
| # plot predictions | |
| lines(preds1$preds ~ preds1$x, col = 'blue') | |
| lines(preds2$preds ~ preds2$x, col = 'red') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment