Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find slope before of a series before and after a given point

I'm studying structural breaks so I have identified a break in my series. I'd like to find the slope of the linear equation (y~x) before and after the break such that the fitted values are joint by the break.

I tried fitting linear regressions independently for each segment or using interactions (with and without an effects) but that just gives me a different "starting point" for each segment, which I want to avoid. I'm thinking something similar to the software Joinpoint but for a case when I already know where the breaks are.

Any ideas or suggestions would be greatly appreciated!!

like image 386
Enrique M. Saldarriaga Avatar asked Sep 13 '25 06:09

Enrique M. Saldarriaga


1 Answers

Given a cutpoint at x = k, a joinpoint regression can be fitted as

y ~ x + ifelse(x <= k, 0, x-k)

Example

The cutpoint is known to be k = 3:

set.seed(123)
x <- rnorm(500, mean = 3)
y <- (x - 3)^2 + rnorm(500)
df <- data.frame(x = x, y = y)

## Joinpoint Regression
jp <- lm(y ~ x + ifelse(x <= 3, 0, x-3), data = df)

# Call:
# lm(formula = y ~ x + ifelse(x <= 3, 0, x - 3),
#    data = data.frame(x = x, y = y))
# 
# Coefficients:
#              (Intercept)                         x  ifelse(x <= 3, 0, x - 3)  
#                    5.590                    -2.079                     4.121

The slopes for the lines before and after x=3 are -2.079 and -2.079+4.121 respectively.

x_horiz <- seq(0, 6, 0.01)
plot(x, y)
lines(x_horiz, predict(jp, newdata = data.frame(x = x_horiz)),
      col = "red", lwd = 2)

enter image description here

like image 55
Darren Tsai Avatar answered Sep 15 '25 19:09

Darren Tsai