英文:
Converting a plotted line into a model object
问题
假设我有一系列点,我想在这些点之间绘制直线:
x <- c(0, 2, 4, 7, 12)
y <- c(0, 0, 4, 5, 0)
plot(x, y, type = 'l')
[![穿过点(2,1)、(6,2)、(7,5)和(12,2)的线图][1]][1]
我应该如何将绘制的线转化为一个简单的模型对象?例如,我应该如何创建一个模型对象,以便可以使用`stats::predict()`函数执行类似以下的操作:
model.object <- ???
predict(model.object, data.frame(x = 3))
输出:
2
或者,至少有没有一种方法可以让R识别这些点之间各条直线的斜率和截距,以便我可以手动使用if语句创建分段函数?
[1]: https://i.stack.imgur.com/4VnsM.png
英文:
Let's say I have a series of points between which I want to plot straight lines:
x <- c(0, 2, 4, 7, 12)
y <- c(0, 0, 4, 5, 0)
plot(x, y, type = 'l')
How would I go about turning this plotted line into a simple model object? For instance, something with which I would be able to use the stats::predict()
function to do something like this:
model.object <- ???
predict(model.object, data.frame(x = 3))
Output:
2
Or, at the very least, is there some way R can identify the slopes and intercepts of each of these lines between the points so I could manually create a piecewise function using if-statements?
答案1
得分: 1
虽然有些不同于 predict
,但可以使用 approxfun
在点之间进行插值:
f <- approxfun(x, y)
f(3)
# [1] 2
需要注意的是,它只接受 x
值的向量,而不是数据框来进行预测。
英文:
While it's a bit different than predict
, you can use approxfun
to do interpolation between points
f <- approxfun(x, y)
f(3)
# [1] 2
Note that it just takes a vector of x
values rather than a data.frame to make predictions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论