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

Pad*_*Pad 7 interpolation r spline extrapolation

采用看起来像这样的数据框,包含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))
Run Code Online (Sandbox Code Playgroud)

我希望在一年中的每一天基于此创建1:365的值序列,主要是为了创建一个新的数据框,从2005年1月1日到2005年12月31日,其中已经填充了来自a的值.样条函数拟合这些现有的12个值.

当我尝试使用以下方法时:

numbers <- df$numbers
x = spline(1:365, numbers)
Run Code Online (Sandbox Code Playgroud)

我明白了

xy.coords中的错误(x,y,setLab = FALSE):'x'和'y'长度不同'

我不确定出了什么问题.

李哲源*_*李哲源 6

很容易摆脱错误,但很难得到一个明智的答案.

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

有许多插值样条:"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
Run Code Online (Sandbox Code Playgroud)

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

所以显然只有y1而且y3没有问题.让我们勾勒出它们.

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)
Run Code Online (Sandbox Code Playgroud)

样条插值/外推

我们可以看到,在推断数据时我们遇到了很大的问题.