简体   繁体   English

如何在R中保存和加载样条插值函数?

[英]How to save and load spline interpolation functions in R?

I need to create thousands and thousands of interpolation splines, each based on 5 pairs of (x, y) values. 我需要创建成千上万的插值样条,每个样条基于5对(x, y)值。 I would like to save them in a database (or csv file). 我想将它们保存在数据库(或csv文件)中。

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? 我如何导出/导入它们,比如文本格式或实际参数数组,以便在需要时重建每个函数?

If you are using the splinefun function from R base package stats , it is very easy to export its construction information. 如果您使用R base package statssplinefun函数,则可以非常轻松地导出其构造信息。

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

The following illustrates what they mean and how we may re-construct the spline manually. 以下说明了它们的含义以及我们如何手动重新构造样条曲线。

There are n = 3 points, (x[i], y[i]) , hence two pieces. 有n = 3个点, (x[i], y[i]) ,因此有两个。

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. 我们看到我们的手动重建是正确的。

Exporting construction information allows us to move away from R and use it elsewhere. 输出施工信息使我们能够远离R并在其他地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM