按组对时间序列进行线性脊柱插值

linear spine interpolation of time-series by groups

我正在处理 1990-2018 年数千家上市公司余额的时间序列 sheet。在某些年份我只有年度余额sheet,而在其他年份我有5个余额sheet,包括1个年度和4个季度余额sheet。我正在尝试使用所有可用的信息。结余日期 sheet 始终在 xxxx-01-01/xxxx-03-31/xxxx-06-30/xxxx-09-30/xxxx-12-31。我select代号、日期、长期责任和短期责任。我想首先将长期负债和短期负债的总和计算为一个新列,然后按每个月的代码编号对新列进行线性脊柱插值。日期格式为月年

code       date type           cl        ll       
 1   1990-12-31    A     56280000         0        
 1   1991-12-31    A     77230000         0        
 1   1992-12-31    A    195893200         0        
 1   1993-01-01    A            0         0        
 1   1994-06-30    A            0         0        
 1   1994-12-31    A            0         0        
 1   1996-12-31    A            0         0        
 2   1991-12-31    A    374334527   3500000   
 2   1992-12-31    A    688472115  19820785  
 2   1993-12-31    A   1135584690  70268722  
 2   1994-12-31    A   1442120726  85175588  
 2   1995-06-30    A   1571620470         0 

我知道如何使用 splinefun 和 na.approx 在时间间隔不变的情况下做到这一点。但我不知道如何处理非常量时间间隔。谢谢!

我刚得到想要的结果。这个想法来自类似的问题 。值得注意的一件事是月份列是字符形式。我需要 as.numeric(month) 先将它们转换为数字。

 DF$month <- format(as.Date(DF$date), "%m")
 DF$year <- format(as.Date(DF$date), "%Y")
 res <- setDT(DF)[, .SD[match(1:12, as.numeric(month))], by = .(year, code)]
 cols <- c("ll", "cl", "ncl")
 Interpolation <- res[, (cols) := 
 lapply(.SD, na.approx, na.rm = FALSE), .SDcols = cols]