Home > Blockchain >  How to extract the slope of the lines before and after the knot point when fitting a spline regressi
How to extract the slope of the lines before and after the knot point when fitting a spline regressi

Time:10-01

Goal: I wish to extract the slope of the line for before and after the knot point in a spline regression (piecewise linear) model (i.e., to extract the two linear models before and after the inflection point).

Example dataframe in which the DV (mean block level) is recorded at 15 sessions:

structure(list(subject = c("participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003", "participant_003","participant_003", "participant_003", "participant_003", "participant_003"), group_no = c("group1", "group1", "group1","group1", "group1", "group1", "group1", "group1", "group1", "group1","group1", "group1", "group1", "group1", "group1"), session = 1:15,mean_block_level = c(1.3, 1.2, 1.6, 1.8, 1.6, 1.9, 2.2, 2, 
1.8, 1.9, 2.2, 2.1, 1.9, 1.9, 2)), class = "data.frame", row.names = c(NA,-15L))

I have fitted a spline regression with a single knot point at session 7 using the following code (note, I haven't used any 'spline' related package to achieve this):

df$X_bar <- ifelse(df$session>7,1,0)
df$diff <- df$session - 7
df$X <- df3$diff*df$X_bar
df

reg <- summary(lm(mean_block_level~ session   X, data = df))
summary(reg)

reg <-lm(mean_block_level~ session   X, data = df)
plot(mean_block_level ~ session, df)
lines(df$session, predict(reg), col = 'green')

The existing posts on this topic tend to use different packages to create their spline models and so don't exactly answer my question (e.g.,

https://stackoverflow.com/questions/29499686/how-to-extract-the-underlying-coefficients-from-fitting-a-linear-b-spline-regres

CodePudding user response:

You can get the slopes from model coefficients: coef(reg)[2] for the first part and sum(coef(reg)[2:3]) for the second part.

Your model has three fitted coefficients:

coef(reg)
# (Intercept)     session           X 
#   1.1095238   0.1321429  -0.1416667

The first two (Intercept, session) give you the intercept and slope for the first part and if you add the third one (X) to the second one, you get the slope for the second part.

  • Related