如何在 R 中拟合分段回归,并约束第一个拟合通过截距..?

How to fit a piecewise regression in R, and constrain the first fit to pass through the intercept..?

我想执行断棒回归,其中第一段的截距被限制为通过原点。

下面的代码使用 R 中的 'segmented' 包将两个线性模型拟合到数据中。

请注意,尽管第一段的回归不通过原点 - 据我所知,分段不允许用户指定第一段的截距应通过原点。

那么,如何执行这样的折线回归,同时限制第一段通过原点..?

## create data with two 'growth' regimes
n <- 100
x <- 1:n
y1 <- x[1:(n/2)] + rnorm(n=n/2, mean = 0, sd=10) 
y2 <-              rnorm(n=n/2, mean = 0, sd=5) + max(y1)
y <- c(y1,y2)
DF <- data.frame(x,y )

## fit a broken-stick regression model 
library(segmented)
LM <- lm(y~x, DF)
Seggie <- segmented(LM, seg.Z=~x, npsi=1, psi=n/2)

## plot the data & the model
plot(Seggie); abline(h=0, lty=2); abline(v=0, lty=2)
points(y ~ x, DF); abline(h=0, lty=2)

很好的例子。

您只需要调整您的公式,使其需要通过原点。您可以通过将 +0 添加到您的因变量来做到这一点。 (参见 ?formula

LM <- lm(y~x+0, DF)
Seggie <- segmented(LM, seg.Z=~x+0, npsi=1, psi=n/2)
plot(Seggie)
abline(h=0, lty=2); abline(v=0, lty=2)
points(y ~ x, DF); abline(h=0, lty=2)