如何在R中获得样条公式?

时间:2022-06-03 14:58:01

The following code will plot points and a spline (obtained by the spline function):

以下代码将绘制点和样条曲线(通过样条函数获得):

x <- 1:7
y <- c(2,1,4,2,5,1,2)
# plot the points
plot(x, y)
# plot the spline
lines(spline(x, y, n = 100, method = "natural"), col = 2)

What I need is the function itself obtained by spline(x, y, n = 100, method = "natural") so I can get the value of y given any x. how can I do that?

我需要的是通过样条函数获得的函数本身(x,y,n = 100,method =“natural”)所以我可以得到任意x的y值。我怎样才能做到这一点?

I tried the code below but it doesn't work

我尝试了下面的代码,但它不起作用

f <- spline(x, y, n = 100, method = "natural")
f(7)

1 个解决方案

#1


Use ?splinefun, as referenced on the ?spline help page.

使用?splinefun,参见?样条帮助页面。

f <- splinefun(x, y, method = "natural")
f(1)
#[1] 2
f(2)
#[1] 1
f(3.5)
#[1] 2.901923

#1


Use ?splinefun, as referenced on the ?spline help page.

使用?splinefun,参见?样条帮助页面。

f <- splinefun(x, y, method = "natural")
f(1)
#[1] 2
f(2)
#[1] 1
f(3.5)
#[1] 2.901923