Segmented Analysis
By- Rounak Choudhary
By- Rounak Choudhary
The segmented package in R is used for regression models with broken-line relationships, also known as piecewise regression or segmented regression. It fits models where the relationship between the predictor(s) and the response changes at one or more breakpoints. The segmented package in R has wide-ranging applications across many fields, wherever relationships between variables are not constant but change at certain thresholds or breakpoints. The segmented package is especially useful in ecology because many ecological processes are nonlinear and exhibit thresholds—points at which the relationship between variables changes abruptly. These thresholds are crucial for understanding how ecosystems respond to environmental stressors, human activity, or natural gradients.
Pre Requirements:- The data should be prepared as follows:
# Install the required packages (only needs to be done once)
install.packages("segmented") # For segmented (piecewise) regression modeling
install.packages("ggplot2") # For advanced plotting (not directly used in this script but useful)
# Load the installed packages into the R session
library(segmented) # Loads functions for segmented regression
library(ggplot2) # Loads functions for advanced graphics (not used in this script)
# Read a CSV file into a data frame. File should have at least two columns: ShrubP and Richness
df <- read.csv("C:/Users/Rounak Choudhary/Desktop/example.csv")
# Fit a basic linear regression model with Richness as the response and ShrubP as the predictor
lm_model <- lm(Richness ~ ShrubP, data = df)
# Display the minimum and maximum values of the ShrubP variable to help choose a reasonable breakpoint guess
range(df$ShrubP)
# Fit a segmented (piecewise linear) regression model with a breakpoint in ShrubP
# seg.Z = ~ ShrubP tells the function to search for a breakpoint in ShrubP
# psi = 27 gives an initial guess for the breakpoint (must be inside the range of ShrubP)
seg_model <- segmented(lm_model, seg.Z = ~ ShrubP, psi = 27)
# Print a detailed summary of the segmented model including:
# - Regression coefficients
# - Estimated breakpoint (psi)
# - Confidence intervals and significance tests
summary(seg_model)
# Extract the estimated breakpoint value from the model
breakpoint <- seg_model$psi[2] # This is the estimated value of ShrubP where the slope changes
# Create a base scatter plot of Richness vs ShrubP
plot(df$ShrubP, df$Richness, pch = 16, main = "Threshold in Tree Cover")
# Add the fitted segmented regression line to the existing plot in red
plot(seg_model, add = TRUE, col = "red")
# Add a vertical dashed blue line at the estimated breakpoint location
abline(v = breakpoint, col = "blue", lty = 2)