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

Drew Morrison dmorrison at seventhwave.org
Thu Aug 6 22:01:42 CEST 2015


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.



More information about the R-help mailing list