如何为数据帧中的事件分配特定值? [英] How to assign specific value to events in a Dataframe?

查看:34
本文介绍了如何为数据帧中的事件分配特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据。

DOY  <- c(1:30) #Day of Year
rain <- c(0,0,0,0,0,0,0,5.5,15.5,20.1,10.4,0,0,0,0,0,0,0,0,7.6,19.2,44.5,3.4,5.5,0,0,0,0,0,0)
DF <- data.frame(DOY=DOY,rain=rain)

我只对下雨天的降雨事件感兴趣。

I am only interested in days, when it is raining, the rainfall events.

DF <- DF[DF$rain > 0,]

df 的输出,其中降雨事件是

Output of df, which are the rainfall events:

DOY rain
8   5.5
9   15.5
10  20.1
11  10.4
20  7.6
21  19.2
22  44.5
23  3.4
24  5.5

在我的示例中,我有两次降雨事件。如果连续两天都没有下雨,那将永远是新事件。
现在我要为每个降雨事件分配一个 ID 。这样的东西是我的预期输出。

In my example I have two rainfall Events. If it's not raining on consecutive days, it is always a new event. Now I want to assign to each rainfall event an ID. Something like this is my expected output.

DOY rain ID
8   5.5  1
9   15.5 1
10  20.1 1
11  10.4 1
20  7.6  2
21  19.2 2
22  44.5 2
23  3.4  2
24  5.5  2


推荐答案

您可以使用:

cumsum(+c(TRUE, diff(DF$DOY) > 1))

这篇关于如何为数据帧中的事件分配特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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