在R中将条件语句与difftime一起使用 [英] Using conditional statements with difftime in R

查看:133
本文介绍了在R中将条件语句与difftime一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:(1)确定 O的第一个实例的日期,然后(2)确定给定 O之后的 A的第一个实例的日期(3)使用difftime计算时间差。 (类似于:特定事件之间的时间计算

The problem: (1) identify the date of the first instance of "O" and then (2) identify the first instance of of "A" after the given "O" (3) to calculate difference in time using difftime. (similar to: Time Calculation Between Specific Events)

问题特别在于(2),标识给定 O之后的 A的第一个实例。

The issue specifically is with (2), identifying the first instance of "A" after the given "O".

数据帧(df ),其中日期和事件列如下所示:

Data frame (df) with columns Date and Event looks like this:

"Date"        "Event"

"2000-09-08"    "A"

"2000-09-11"    "N"

"2000-09-12"    "O"

"2000-09-13"    "O"

"2000-09-14"    "O"

"2000-09-15"    "O"

"2000-09-18"    "N"

"2000-09-19"    "N"

"2000-09-20"    "N"

"2000-09-21"    "N"

"2000-09-22"    "N"

"2000-09-25"    "A"

"2000-09-26"    "A"

"2000-09-27"    "A" 

"2000-09-28"    "A"

"2000-09-29"    "A"

"2000-10-02"    "A"

"2000-10-03"    "A"

,第一个 O出现在2000-09-12,第二个 A出现在2000-09-25。

For example, the first "O" occurs at 2000-09-12 and the first "A" after it occurs at 2000-09-25.

对于代码:
这样可以正确识别 O的第一个实例

As for the code: this correctly identifies first instance of "O"

df$Date[df$Event=="O"] [1]
"2000-09-12" #correct

但这会错误地标识第一个df的 A,而不是 O之后的第一个

but this incorrectly identifies the first "A" of df, not the first one after "O"

df$Date[df$Event=="A"] [1]
"2000-09-12" ##WRONG, correct == "2000-09-25"

,它标识 A的实例,它是集合中第(每个 O的##)个数

and this identifies the instance of "A" that is the (## of each "O")th of the set

df$Date[df$Event=="A"] [df$Event=="O"]

"2000-10-23" "2000-10-24" "2000-10-25" "2000-10-26" "2001-04-03" "2001-04-04" "2001-06-29"....

我只需要编写此条件来查找给定 O后的第一个A,以便difftime给出正确的天数。

I just need help writing this conditional to find the first A after the given "O" in order for difftime to give the correct number of days.

推荐答案

这不要求待排序的日期

date1 <- min(df$Date[df$Event == "O"])
date2 <- min(df$Date[df$Event == "A" & df$Date > date1])

difftime(date2, date1)
Time difference of 13 days

这篇关于在R中将条件语句与difftime一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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