[R] Piecewise (segmented) linear regression with center section slope constraint

Adams, Jean jvadams at usgs.gov
Fri Aug 7 14:54:48 CEST 2015


This posting on StackOverflow might be useful to you.
http://stackoverflow.com/questions/13810607/in-r-package-segmented-how-could-i-set-the-slope-of-one-of-lines-in-the-model

Jean

On Thu, Aug 6, 2015 at 3:01 PM, Drew Morrison <dmorrison at seventhwave.org>
wrote:

> Hi,
>
> I'm working on a way to predict the electricity consumption of electrically
> heated buildings as a function of outdoor air temperature. I've identified
> a
> three-segment linear model as a candidate for a good fit, with the slope of
> the center section constrained to zero. I'm working with the segmented
> package. I've searched some of the other posts on this forum and they've
> been very helpful, but they don't address my big sticking point: how do I
> constrain the slope of the center section of the model to 0, rather than
> the
> left or right section?
>
> Below is a script with simulated data and my first attempt at fitting the
> model. You should be able to copy, paste, and run it. Thanks in advance.
> Drew
>
> # three-piece segmented regression
> # center section constrained to slope of 0.
>
>
> # simulate and plot data
> T<- 1:100
> energy<- 100+75*pmax(55-T,0)+25*pmax(T-70,0)+150*rnorm(50)
> plot(T, energy)
>
> # create a linear model
> model <- lm(energy~T)
> #print(summary(model))
>
> # start segmented regression
> library(segmented)
> seg_model <- segmented(model, seg.Z = ~ T, psi = list(T = c(52, 71)))
> print(summary(seg_model))
> print(seg_model$psi)
> print(slope(seg_model))
>
> # plot regression lines
> fitted_energy <- fitted(seg_model)
> regression_model <- data.frame(Temperature = T, kWh = fitted_energy)
> lines(x = T, y = fitted_energy, col = 1)
>
> # try constrained regression
> TT<- -T   # change signs of independent variable
> model <- lm(energy~1)  # constrain slope
> seg_model <- segmented(model, seg.Z = ~ TT, psi = list(TT = c(-71, -52)))
> print(summary(seg_model))
> print(seg_model$psi)
> print(slope(seg_model))
>
> # plot constrained regression
> fitted_energy <- fitted(seg_model)
> regression_model <- data.frame(Temperature = T, kWh = fitted_energy)
> lines(x = T, y = fitted_energy, col = 2)
>
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/Piecewise-segmented-linear-regression-with-center-section-slope-constraint-tp4710839.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list