Search code examples
rpiecewise

How can I pull slope and intercept variables produced by the segmented package and put into a dataframe using r?


Can anyone walk me through how to get the slopes and intercepts produced by the segmented package out and placed in a data frame? This will ultimately be used to line up slopes and intercepts back to their original value. See data (that I took from another post) below.

#load packages library(segmented) library(tidyverse)

#set seed and develop data
set.seed(1)
Y<-c(13,21,12,11,16,9,7,5,8,8)
X<-c(74,81,80,79,89,96,69,88,53,72)
age<-c(50.45194,54.89382,46.52569,44.84934,53.25541,60.16029,50.33870,
   51.44643,38.20279,59.76469)
dat=data.frame(Y=Y,off.set.term=log(X),age=age)

#run initial GLM
glm.fit=glm(Y~age+off.set.term,data=dat,family=poisson)
summary(glm.fit)

#run segmented glm
glm.fitted.segmented <- segmented(glm.fit, seg.Z=~age + off.set.term, psi = 
list(age = c(50,53), off.set.term = c(4.369448)))

#Get summary, slopes and intercepts
summary(glm.fitted.segmented)
slope(glm.fitted.segmented)
intercept(glm.fitted.segmented)

Solution

  • library(broom)
    library(dplyr)
    library(tidyr)
    library(stringr)
    
    slopes <-
      bind_rows(lapply(slope(glm.fitted.segmented), tidy), .id = "variable") %>%
      mutate(type = str_extract(.rownames, "^[a-z]+"),
             model = str_extract(.rownames, "[0-9]+$")) %>%
      select(variable, model, type, estimate = "Est.")
    intercepts <-
      bind_rows(lapply(intercept(glm.fitted.segmented), tidy), .id = "variable") %>%
      mutate(type = str_extract(.rownames, "^[a-z]+"),
             model = str_extract(.rownames, "[0-9]+$")) %>%
      select(variable, model, type, estimate = "Est.")
    
    bind_rows(slopes, intercepts) %>%
      spread(type, estimate)
    

    Using the tidy function, you can easily pull out the data.frame for each variable then extract the model and type of unit. Bind it all together and spread the type and estimate value to end with variable, model, intercept, and slope.