在 R 中查找观察之间的天数 [英] Find number of days between observations in R

查看:38
本文介绍了在 R 中查找观察之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间序列数据集(每天观察一次).我想要做的是找到数据集中每一天的观察值高于零的天数.

I have a dataset in time series (an observation per day). What I would like to do is find the number of days until an observation is above zero for each day in the dataset.

数据集示例如下所示:

Date        Runoff
01/01/1980  0
02/01/1980  0
03/01/1980  0
04/01/1980  0
05/01/1980  4.5
06/01/1980  2
07/01/1980  0
08/01/1980  0
09/01/1980  0
10/01/1980  0
11/01/1980  0
12/01/1980  0
13/01/1980  1.2
14/01/1980  0 
15/01/1980  0
16/01/1980  0
17/01/1980  0
18/01/1980  0.8

而我想要的是:

Date        Runoff   No_Days
01/01/1980  0        4
02/01/1980  0        3
03/01/1980  0        2
04/01/1980  0        1
05/01/1980  4.5      0
06/01/1980  2        0
07/01/1980  0        6
08/01/1980  0        5
09/01/1980  0        4
10/01/1980  0        3
11/01/1980  0        2
12/01/1980  0        1  
13/01/1980  1.2      0
14/01/1980  0        4      
15/01/1980  0        3
16/01/1980  0        2
17/01/1980  0        1
18/01/1980  0.8      0

因此,您可以看到特定日期是否有径流,那么距离径流还有 0 天,如果第二天有径流事件,则距离径流还有 1 天.

So as you can see if there is runoff on a particular date then there are 0 days until runoff, if there is a runoff event the next day then there is 1 day until runoff etc.

我已经使用 R 一段时间了,这是我第一次找不到解决方案,因此这是我在这里的第一个 R 相关问题,所以请放轻松!

I've been using R for a while and this is the first time I haven't been able to find a solution hence this is my first R related question on here so please go easy on me!

如果我错过了什么,请不要犹豫,让我知道.

If I've missed anything don't hesitate to let it be known.

谢谢,

J

推荐答案

我也在考虑rleseq_len:

df$No_Days <- unlist(sapply(rle(df$Runoff)$lengths, 
                            function(x) 
                              if (x>1) 
                                rev(seq_len(x)) 
                              else 0))

这篇关于在 R 中查找观察之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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