用 R 计算时间序列中的间隙大小 [英] Gap size calculation in time series with R

查看:34
本文介绍了用 R 计算时间序列中的间隙大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含时间序列的数据框,如下所示:

Let's say I have a dataframe with contains time series as below:

Date                value
2000-01-01 00:00:00  4.6
2000-01-01 01:00:00  N/A
2000-01-01 02:00:00  5.3
2000-01-01 03:00:00  6.0
2000-01-01 04:00:00  N/A
2000-01-01 05:00:00  N/A
2000-01-01 06:00:00  N/A
2000-01-01 07:00:00  6.0

我想找到一种有效的方法来计算差距的大小(连续 N/As 的数量)并将其添加到我的数据框的新列中以获得以下内容:

I want to find an efficient way to calculate the size of the gap (number of consecutive N/As) and add it to a new column of my dataframe to get the following:

Date                value  gap_size
2000-01-01 00:00:00  4.6      0
2000-01-01 01:00:00  N/A      1
2000-01-01 02:00:00  5.3      0
2000-01-01 03:00:00  6.0      0
2000-01-01 04:00:00  N/A      3
2000-01-01 05:00:00  N/A      3
2000-01-01 06:00:00  N/A      3
2000-01-01 07:00:00  6.0      0

我的数据框实际上有超过 600 万行,所以我正在寻找计算方面最便宜的方法.请注意,我的时间序列在整个数据集上是等距分布的(1 小时).

My dataframe in reality has more than 6 millions row so I am looking for the cheapest way in terms of computation. Note that my time series is equi-spaced over the whole dataset (1 hour).

推荐答案

在这种情况下,您可以尝试使用 rle 来生成游程长度.首先,使用 is.na 将您的值列转换为逻辑值,并应用 rle 提供输入向量不同值的运行长度.在这种情况下,这两个类别是 TRUE 和 FALSE,您正在计算它们运行的​​时间.然后,您可以rep通过运行长度来说明这一点,以获得您正在寻找的输出.

You could try using rle in this case to generate run lengths. First, convert your value column to logical using is.na and apply rle which provides the run lengths of the different values of the input vector. In this case, the two categories are TRUE and FALSE, and you're counting how long they run for. You can then replicate this by the run length to get the output you're looking for.

x = c(1,2,4,NA,NA,6,NA,19,NA,NA)
res = rle(is.na(x))
rep(res$values*res$lengths,res$lengths)
#> [1] 0 0 0 2 2 0 1 0 2 2

这篇关于用 R 计算时间序列中的间隙大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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