如何在R语言中构建分段常数(箱线平滑)模型?
Hey Jack, nice question! I've run into this exact scenario before, so let's walk through how to fit a piecewise constant regression model in R that's suitable for prediction—no regressogram required.
Method 1: Using the segmented Package (Automatic Breakpoint Estimation)
Since you're already familiar with the segmented package, we can adapt it to enforce zero slopes for all segments (which is exactly what a piecewise constant model is: each segment is a flat line). Here's how to do it step by step:
Load packages and prepare data
First, let's set up some sample data to work with (you can replace this with your own dataset):library(segmented) set.seed(123) # For reproducibility # Simulate data with 3 constant segments x <- seq(0, 10, length.out = 100) y <- rep(c(2, 5, 3), each = 34)[1:100] + rnorm(100, 0, 0.5) df <- data.frame(x, y)Fit an initial linear model
Thesegmentedpackage needs a starting model to build from—we'll use a simple linear regression as the baseline:lm_init <- lm(y ~ x, data = df)Fit the piecewise constant model
The key here is thefix.slope = 0argument, which forces all segments to have a slope of 0 (i.e., constant values). We also provide initial guesses for breakpoints withpsi(you can get these from plotting your data first to spot obvious shifts):# Fit model with 2 breakpoints (creating 3 constant segments) seg_fit <- segmented(lm_init, seg.Z = ~x, psi = c(3, 7), # Initial guess for breakpoints fix.slope = 0) # Enforce zero slopes for all segmentsInspect results and make predictions
You can check the model output to see the estimated breakpoints and constant values for each segment, then usepredict()just like any other regression model:# View model summary summary(seg_fit) # Predict for new x values new_data <- data.frame(x = c(1, 4, 8)) predict(seg_fit, newdata = new_data)
Method 2: Manual Dummy Variables (Known Breakpoints)
If you already know where your breakpoints should be (e.g., from domain knowledge), you can build the model manually using dummy variables. This is super straightforward and easy to interpret:
Create interval categories
Usecut()to split your predictorxinto intervals based on your breakpoints:# Define breakpoints (e.g., 3 and 7) df$x_group <- cut(df$x, breaks = c(-Inf, 3, 7, Inf), labels = c("low", "mid", "high"))Fit the constant model
Now just fit a linear regression with the categorical group variable—each group's coefficient will be the constant value for that segment:dummy_fit <- lm(y ~ x_group, data = df)Make predictions
When predicting, just make sure your new data uses the same factor levels:# Predict for a value in the "mid" group predict(dummy_fit, newdata = data.frame(x_group = factor("mid", levels = c("low", "mid", "high"))))
Quick Tips
- For the
segmentedmethod, good initial guesses for breakpoints (psi) are crucial—plot yourxvsyfirst to spot where the constant levels shift. - If you only want some segments to be constant (not all), you can pass a vector to
fix.slope(e.g.,fix.slope = c(0, 1)to make the first segment constant and the second have a slope).
内容的提问来源于stack exchange,提问作者user6429576

