将绘制的线转换为模型对象

huangapple go评论60阅读模式
英文:

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 &lt;- c(0, 2, 4, 7, 12)
y &lt;- c(0, 0, 4, 5, 0)
plot(x, y, type = &#39;l&#39;)

将绘制的线转换为模型对象

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 &lt;- ???

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 &lt;- 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.

huangapple
  • 本文由 发表于 2023年2月7日 01:59:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定