在 R 中拟合样条函数以从月值中插入日值

Fitting a spline function in R to interpolate daily values from monthly values

采用如下所示的数据框,其中包含 2005 年某些日期的数据以及每个日期的测量值。

df <- data.frame("date" = c('2005-04-04','2005-04-19', '2005-04-26', '2005-05-05', 
'2005-05-12', '2005-05-25', '2005-06-02', '2005-06-16', '2005-07-07', '2005-07-14', 
'2005-07-21', '2005-08-04'), "numbers" = c(90,50,50,48,44,37,34,30,36,31,49,54))

我想基于此为一年中的每一天创建一个来自 1:365 的值序列,本质上是创建一个从 01/01/2005 到 31/12/2005 的新数据框,它具有填充了拟合这些现有 12 个值的样条函数的值。

当我尝试使用以下方式执行此操作时:

numbers <- df$numbers
x = spline(1:365, numbers)

我明白了

Error in xy.coords(x, y, setLab = FALSE) : 'x' and 'y' lengths differ'

我不确定出了什么问题。

消除错误很容易,但很难得到一个明智的答案。

x <- as.POSIXlt(as.character(df$date))$yday + 1  ## day of year (start from 1)
y <- df$number

有多种插值样条:"fmm"、"periodic"、"natural"、"monoH.FC"和"hyman"。但并不是所有的都适用于此。

y1 <- spline(x, y, xout = 1:365, method = "fmm")

y2 <- spline(x, y, xout = 1:365, method = "periodic")
#Warning message:
#In spline(x, y, xout = 1:365, method = "periodic") :
#  spline: first and last y values differ - using y[1] for both

y3 <- spline(x, y, xout = 1:365, method = "natural")

y4 <- spline(x, y, xout = 1:365, method = "monoH.FC")
#Error in spline(x, y, xout = 1:365, method = "monoH.FC") : 
#  invalid interpolation method

y5 <- spline(x, y, xout = 1:365, method = "hyman")
#Error in spline(x, y, xout = 1:365, method = "hyman") : 
#  'y' must be increasing or decreasing

有关这些方法的详细信息以及对它们的必要假设/要求,请参阅?spline

所以显然只有y1y3没有问题得到了。让我们画出它们。

par(mfrow = c(1, 2))
plot(y1, type = "l", main = "fmm"); points(x, y, pch = 19)
plot(y3, type = "l", main = "natural"); points(x, y, pch = 19)

正如我们所见,我们在外推数据时遇到了大问题