如何在同一数据中拟合两个线性回归?

时间:2019-11-22 04:27:31

标签: r statistics

可能听起来很愚蠢,但我说:

x = c(1:10)
y = c(2,4,6,8,10,12,12.5,13,13.5,14)

散点图如下:

enter image description here

我想拟合两个线性回归方程,而不是拟合一个线性回归。 x> a 和等式时为1。 2当x <= a 。并从斜率变化时找到 a 值。在此示例中,通过视觉分析 a 大约为6,但是有没有办法更自动地找到它?

我正在寻找的东西是这样的:

enter image description here

2 个答案:

答案 0 :(得分:4)

CRAN软件包segmented非常适合此类问题。它甚至简单易用。首先拟合线性模型,然后获得分段拟合。

library(segmented)

x <- 1:10
y <- c(2,4,6,8,10,12,12.5,13,13.5,14)

fit <- lm(y ~ x)
segfit <- segmented(fit)

现在是断点。 segfit$psi[2]是断点。

segfit$psi
#       Initial Est.       St.Err
#psi1.x     5.5    6 6.452643e-16

摘要提供了更多信息。

summary(segfit)

并绘制图形。

plot(x, y)
plot(segfit, add=TRUE)

enter image description here

答案 1 :(得分:0)

绘制时:

scatter.smooth(x,y) 

您可以得到一行: stating where is your break point or threshold point

除此之外,您还可以循环查看坡度变化的地方:

for(i in 1:length(x)){
slope = (y[i+1]-y[i]/(x[i+1]-x[i]))
  print(paste(i,slope))
}

希望这会有所帮助。