rpiecewise

emtrends and piecewise regression


I want to obtain four slopes for piecewise regression. Two slopes for each release type before 365 days, and after 365 days. I also know I should use the emmeans package.

Here is a dummy dataset.

 df <- data.frame (tsr = c(0,0,9,10,19,20,20,21, 30,30,100,101,200,205,350,360, 400,401,500,501,600,605,700,710,800,801,900,902,1000,1001,1100,1105,2000,2250,2500,2501),
              release_type = c('S','H','S','H','S','S','H','S','H','S','S','H','S','H','S','S','H','S','H','S','S','H','S','H','S','S','H','S','H','S','S','H','S','H','S', 'H'),
              cond = c(250,251,250,251,300,301,351,375,250,249,216,257,264,216,250,251,250,251,300,301,351,375,250,249,216,257,264,216, 250,251,250,251,300,301,351,375),
              notch = c('A','B','C','D','A','B','C','D','A','B','C','D','E','G','E','G','A','H','J','K','L','Q','W','E','R','Y','U','I','O','P','Y','U','I','O','P', 'Z'))

 #Load libraries
 library(emmeans)
 library(lme4)

 #Set up break point manually
 bp = 365
 b1 <- function(x, bp) ifelse(x < bp, bp - x, 0)
 b2 <- function(x, bp) ifelse(x < bp, 0, x - bp)
 
 #Fit linear mixed effect model using piecewise regression
 m1 <- lmer(cond~b1(tsr, bp) + b2(tsr,bp) + b1(tsr, bp):release_type 
       + b2(tsr,bp):release_type + release_type + (1|notch), data = df)

 #Obtain slopes
 emtrends(m1, params = "bp", var = "tsr", pairwise ~ release_type)

I am only getting estimates for one slope of each release type. What am I doing wrong?

Note: I cannot use the summary() function to obtain slopes because it uses the function above to generate those estimates. So it is not the pure slopes.


Solution

  • You have to add at = list(tsr = c(10, 400)) to the emtrends() call to specify representative times before and after the breakpoint. Otherwise, it just uses the average value of tsr since it is a quantitative predictor.

    Update

    You need to specify tsr also. Otherwise it will average over the two values of tsr.

    > emtrends(m1, params = "bp", var = "tsr", ~ release_type*tsr, at = list(tsr=c(10,400)))
    NOTE: Results may be misleading due to involvement in interactions
     release_type tsr tsr.trend     SE   df lower.CL upper.CL
     H             10   -0.0170 0.0932 30.0 -0.20743   0.1734
     S             10   -0.0894 0.0759 25.5 -0.24569   0.0668
     H            400    0.0343 0.0215 30.0 -0.00970   0.0782
     S            400    0.0341 0.0214 29.3 -0.00963   0.0778
    
    Degrees-of-freedom method: kenward-roger 
    Confidence level used: 0.95 
    

    If you had read the annotations below the output when tsr was omitted, this would have been evident.