如何在R中保存和加载样条插值函数? [英] How to save and load spline interpolation functions in R?
问题描述
我需要创建成千上万的插值样条,每个样条基于5对(x,y)
值。我想将它们保存在数据库(或csv文件)中。
I need to create thousands and thousands of interpolation splines, each based on 5 pairs of (x, y)
values. I would like to save them in a database (or csv file).
如何导出/导入它们,比如文本格式或实际参数数组在需要时重建每个函数?
How can I export / import them, say in a text format or as an array of real parameters to rebuild each function when I need them?
推荐答案
如果你使用 splinefun
来自R base package的函数 stats
,可以很容易地导出其构造信息。
If you are using the splinefun
function from R base package stats
, it is very easy to export its construction information.
set.seed(0)
xk <- c(0, 1, 2)
yk <- round(runif(3), 2)
f <- splinefun(xk, yk, "natural") ## natural cubic spline
construction_info <- environment(f)$z
str(construction_info)
# $ method: int 2
# $ n : int 3
# $ x : num [1:3] 0 1 2
# $ y : num [1:3] 0.9 0.27 0.37
# $ b : num [1:3] -0.812 -0.265 0.282
# $ c : num [1:3] 0 0.547 0
# $ d : num [1:3] 0.182 -0.182 0
以下说明了它们的含义以及我们如何重建splin e手动。
The following illustrates what they mean and how we may re-construct the spline manually.
有n = 3分,(x [i],y [i])
,因此有两件。
There are n = 3 points, (x[i], y[i])
, hence two pieces.
attach(construction_info)
## plot the interpolation spline in gray
curve(f(x, 0), from = x[1], to = x[n], lwd = 10, col = 8)
## highlight knots
points(x, y, pch = 19)
## piecewise re-construction
piece_cubic <- function (x, xi, yi, bi, ci, di) {
yi + bi * (x - xi) + ci * (x - xi) ^ 2 + di * (x - xi) ^ 3
}
## loop through pieces
for (i in 1:(n - 1)) {
curve(piece_cubic(x, x[i], y[i], b[i], c[i], d[i]), from = x[i], to = x[i + 1],
add = TRUE, col = i + 1)
}
detach(construction_info)
我们看到我们的手动重建是正确的。
We see that our manual re-construction is correct.
导出建筑信息使我们可以远离R并在其他地方使用它。
Exporting construction information allows us to move away from R and use it elsewhere.
这篇关于如何在R中保存和加载样条插值函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!