Skip to content

Instantly share code, notes, and snippets.

@smrmkt
Last active August 29, 2015 14:14
Show Gist options
  • Save smrmkt/26972192b86df89b2159 to your computer and use it in GitHub Desktop.
Save smrmkt/26972192b86df89b2159 to your computer and use it in GitHub Desktop.
two-piece linear regression model
data(cars)
t=21
# y = α + βx + γ(x > t)(x - t + 1) + ε
cars$speed_t <- (cars$speed>t)*(cars$speed-t)
cars.lm <- lm(dist~speed+speed_t, data=cars)
summary(cars.lm)
# plot scatter and line
plot(cars$speed, cars$dist)
lines(cars$speed, cars.lm$fitted.values)
data(JohnsonJohnson)
p=40
# y = α + βx + γ(x > t)(x - t + 1) + ε
t = c(1:84)
JJ2 = as.data.frame(cbind(JohnsonJohnson, t, (t>p)*(t-p)))
colnames(JJ2) = c('earnings', 't', 't2')
JJ2.lm <- lm(earnings~t+t2, data=JJ2)
summary(JJ2.lm)
# plot scatter and line
plot(JJ2$t, JJ2$earnings)
lines(JJ2$t, JJ2.lm$fitted.values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment