【发布时间】:2019-01-04 23:44:04
【问题描述】:
我今天正在帮助一位朋友进行分段回归。我们试图用断点拟合分段回归,看看它是否比标准线性模型更适合数据。
我偶然发现了一个我无法理解的问题。当使用提供的数据拟合具有单个断点的分段回归时,它确实适合单个断点。
但是,当您从模型进行预测时,它会给出看起来像 2 个断点的情况。使用plot.segmented() 绘制模型时不会发生此问题。
任何人都知道发生了什么以及如何获得正确的预测(和标准错误等)?或者我在一般代码中做错了什么?
# load packages
library(segmented)
# make data
d <- data.frame(x = c(0, 3, 13, 18, 19, 19, 26, 26, 33, 40, 49, 51, 53, 67, 70, 88
),
y = c(0, 3.56211608128595, 10.5214485148819, 3.66063708049802, 6.11000808621074,
5.51520423804034, 7.73043895812661, 7.90691392857039, 6.59626527933846,
10.4413913666936, 8.71673928545967, 9.93374157928462, 1.214860139929,
3.32428882257746, 2.65223361387063, 3.25440939462105))
# fit normal linear regression and segmented regression
lm1 <- lm(y ~ x, d)
seg_lm <- segmented(lm1, ~ x)
slope(seg_lm)
#> $x
#> Est. St.Err. t value CI(95%).l CI(95%).u
#> slope1 0.17185 0.094053 1.8271 -0.033079 0.37677000
#> slope2 -0.15753 0.071933 -2.1899 -0.314260 -0.00079718
# make predictions
preds <- data.frame(x = d$x, preds = predict(seg_lm))
# plot segmented fit
plot(seg_lm, res = TRUE)
# plot predictions
lines(preds$preds ~ preds$x, col = 'red')
由reprex package (v0.2.0) 于 2018 年 7 月 27 日创建。
【问题讨论】:
标签: r regression linear-regression lm piecewise