如何在R中重新采样和插值时间序列数据?

时间:2012-07-09 04:01:52

标签: r time-series interpolation

我的测量大约每5分钟记录一次:

2012-07-09T05:30:01+02:00   1906.1  1069.2  1093.2  3   1071.0  1905.7  
2012-07-09T05:35:02+02:00   1905.7  1069.2  1093.0  0   1071.5  1905.7  
2012-07-09T05:40:02+02:00   1906.1  1068.7  1093.2  0   1069.4  1905.7  
2012-07-09T05:45:02+02:00   1905.7  1068.4  1093.0  1   1069.6  1905.7  
2012-07-09T05:50:02+02:00   1905.7  1068.2  1093.0  4   1073.3  1905.7  

第一列是数据的时间戳。其余列是记录的数据。

我需要重新采样我的数据,以便每15分钟有一行,例如类似的东西:

2012-07-09T05:15:00 XX XX XX XX XX XX
2012-07-09T05:30:00 XX XX XX XX XX XX
....

(此外,记录的数据可能存在差距,我希望用一行NA值代替一小时以上的差距。)

我可以想到几种方法来手动编程,但是有内置的支持在R中做那种东西吗?我查看了处理时间序列数据的不同库(zoochron等),但找不到任何令人满意的结果。

4 个答案:

答案 0 :(得分:6)

You can use approx or the related approxfun. If t is the vector consisting of the timepoints where your data was sampled and if y is the vector with the data then f <- approxfun(t,y) creates a function f that linearly interpolates the data points in between the time points.

Example:

# irregular time points at which data was sampled
t <- c(5,10,15,25,30,40,50)
# measurements 
y <- c(4.3,1.2,5.4,7.6,3.2,1.2,3.7)

f <- approxfun(t,y)

# get interpolated values for time points 5, 20, 35, 50
f(seq(from=5,to=50,by=15))
[1] 4.3 6.5 2.2 3.7

答案 1 :(得分:0)

在CrossValidated上对此进行了很好的讨论:https://stats.stackexchange.com/questions/31666/how-can-i-align-synchronize-two-signals。该答案的作者“推出了他自己的”插值和重新采样代码。

答案 2 :(得分:0)

如果您正在寻找内置的下采样(不支持上采样),您也可以使用xts包。

data(sample_matrix)
samplexts <- as.xts(sample_matrix)
to.monthly(samplexts)
to.yearly(samplexts)

答案 3 :(得分:-5)

你应该看一下openair包,里面有很多用于播放时间序列数据的“工具”。