如果您有拟合模型,那么最好的解决方案是使用该predict()
方法为感兴趣的区间上的一组等距点生成预测。
使用来自@thelatemail 答案的数据
df <- data.frame(y = c(1.4, 2.3, 3.8, 3.6, 5.9, 5.4, 7.6, 7.4, 8.1,
8.7, 7.4, 6.9, 5.4, 4.7, 2.7, 1.8, 1.1),
x = 1:17,
ind = rep(c(TRUE,FALSE), times = c(8,9)))
fit1 <- lm(y ~ x, data = df, subset = ind)
fit2 <- lm(y ~ x, data = df, subset = !ind)
## regions in a new data frame over which to predict
r1 <- data.frame(x = seq(from = 1, to = 8, length.out = 20))
r2 <- data.frame(x = seq(from = 9, to = 17, length.out = 20))
## predict
p1 <- predict(fit1, newdata = r1)
p2 <- predict(fit2, newdata = r2)
## add lines to plot
plot(y ~ x, data = df, type = "l")
lines(p1 ~ x, data = r1, col = "red")
lines(p2 ~ x, data = r2, col = "blue")
这给

这是一种比手动写出方程式更灵活的方法,并且适用于许多类型的模型,它们都有predict()
方法。