在 R 中使用线性插值添加缺失的 xts/zoo 数据 [英] Add missing xts/zoo data with linear interpolation in R

查看:28
本文介绍了在 R 中使用线性插值添加缺失的 xts/zoo 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有丢失数据的问题,但我没有 NA - 否则会更容易处理...

I do have problems with missing data, but I do not have NAs - otherwise would be easier to handle...

我的数据如下所示:

time, value
2012-11-30 10:28:00, 12.9
2012-11-30 10:29:00, 5.5
2012-11-30 10:30:00, 5.5
2012-11-30 10:31:00, 5.5
2012-11-30 10:32:00, 9
2012-11-30 10:35:00, 9
2012-11-30 10:36:00, 14.4
2012-11-30 10:38:00, 12.6

如您所见 - 缺少一些分钟值 - 它是 xts/zoo 所以我使用 as.POSIXct... 将日期设置为索引.如何添加缺失的时间步以获得完整的 ts?我想用线性插值填充缺失值.

As you can see - there are missing some minute values - it is xts/zoo so I use as.POSIXct... to set the date as an index. How to add the missing timesteps to get a full ts? I want to fill the missing values with linear interpolation.

感谢您的帮助!

推荐答案

您可以合并您的数据与包含所有日期的向量.之后,您可以使用 na.approx 来填充空格(在本例中为 NA).

You can merge your data with a vector with all dates. After that you can use na.approx to fill in the blanks (NA in this case).

data1 <-read.table(text="time, value
2012-11-30-10:28:00, 12.9
2012-11-30-10:29:00, 5.5
2012-11-30-10:30:00, 5.5
2012-11-30-10:31:00, 5.5
2012-11-30-10:32:00, 9
2012-11-30-10:35:00, 9
2012-11-30-10:36:00, 14.4
2012-11-30-10:38:00, 12.6", header = TRUE, sep=",", as.is=TRUE)
times.init <-as.POSIXct(strptime(data1[,1], '%Y-%m-%d-%H:%M:%S'))
data2 <-zoo(data1[,2],times.init)
data3 <-merge(data2, zoo(, seq(min(times.init), max(times.init), "min")))
data4 <-na.approx(data3)

这篇关于在 R 中使用线性插值添加缺失的 xts/zoo 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆