计算自 R 中上次事件以来的天数 [英] Calculate days since last event in R

查看:26
本文介绍了计算自 R 中上次事件以来的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题涉及如何计算自上次在 R 中发生的事件以来的天数.以下是数据的最小示例:

My question involves how to calculate the number of days since an event last that occurred in R. Below is a minimal example of the data:

df <- data.frame(date=as.Date(c("06/07/2000","15/09/2000","15/10/2000","03/01/2001","17/03/2001","23/05/2001","26/08/2001"), "%d/%m/%Y"), 
event=c(0,0,1,0,1,1,0))
        date event
1 2000-07-06     0
2 2000-09-15     0
3 2000-10-15     1
4 2001-01-03     0
5 2001-03-17     1
6 2001-05-23     1
7 2001-08-26     0

二进制变量(事件)的值为 1 表示事件发生,否则为 0.在不同时间进行重复观察(date)预期输出如下,自上次事件(tae)以来的天数:

A binary variable(event) has values 1 indicating that the event occurred and 0 otherwise. Repeated observations are done at different times(date) The expected output is as follows with the days since last event(tae):

 date        event       tae
1 2000-07-06     0        NA
2 2000-09-15     0        NA
3 2000-10-15     1         0
4 2001-01-03     0        80
5 2001-03-17     1       153
6 2001-05-23     1        67
7 2001-08-26     0        95

我四处寻找类似问题的答案,但它们没有解决我的具体问题.我试图实现来自来自类似的帖子(计算自上次事件以来经过的时间),下面是最接近我得到了解决方案:

I have looked around for answers to similar problems but they don't address my specific problem. I have tried to implement ideas from from a similar post (Calculate elapsed time since last event) and below is the closest I got to the solution:

library(dplyr)
df %>%
  mutate(tmp_a = c(0, diff(date)) * !event,
         tae = cumsum(tmp_a))

产生如下所示的输出并不完全符合预期:

Which yields the output shown below that is not quite the expected:

        date event tmp_a tae
1 2000-07-06     0     0   0
2 2000-09-15     0    71  71
3 2000-10-15     1     0  71
4 2001-01-03     0    80 151
5 2001-03-17     1     0 151
6 2001-05-23     1     0 151
7 2001-08-26     0    95 246

任何有关如何微调此方法或不同方法的帮助将不胜感激.

Any assistance on how to fine tune this or a different approach would be greatly appreciated.

推荐答案

你可以试试这样的:

# make an index of the latest events
last_event_index <- cumsum(df$event) + 1

# shift it by one to the right
last_event_index <- c(1, last_event_index[1:length(last_event_index) - 1])

# get the dates of the events and index the vector with the last_event_index, 
# added an NA as the first date because there was no event
last_event_date <- c(as.Date(NA), df[which(df$event==1), "date"])[last_event_index]

# substract the event's date with the date of the last event
df$tae <- df$date - last_event_date
df

#        date event      tae
#1 2000-07-06     0  NA days
#2 2000-09-15     0  NA days
#3 2000-10-15     1  NA days
#4 2001-01-03     0  80 days
#5 2001-03-17     1 153 days
#6 2001-05-23     1  67 days
#7 2001-08-26     0  95 days

这篇关于计算自 R 中上次事件以来的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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