Created
October 9, 2012 06:55
-
-
Save certifiedwaif/3857052 to your computer and use it in GitHub Desktop.
lattice panel function to display a segmented regression
This file contains 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
# FIXME: There's a bug where if data in one of the groups is shorter than the others, spurious predictions | |
# from the segmented linear model will be repeated until the number of predictions is the same as the other | |
# data sequences. | |
panel.segmented_lm <- function(x, y, groups, subscripts, ...) | |
{ | |
g = groups[subscripts] | |
for (group in levels(g)) { | |
x2 = x[g==group] | |
y2 = y[g==group] | |
if (length(x2) == 0 || length(y2) == 0) | |
next | |
lm_fit = lm(y2~x2) | |
# If segmented regression fails, fall back to the simple linear regression | |
segmented_fit = tryCatch(segmented(lm_fit, seg.Z=~x2, psi=list(x2=c(mean(x2)))), | |
error = function(e) { | |
lm_fit | |
}) | |
panel.lines(x2, predict(segmented_fit), col = "black") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment