Using conditional statements with difftime in R

大兔子大兔子 提交于 2019-12-13 00:23:36

问题


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)

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

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"

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

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

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

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"

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"....

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.


回答1:


This does not require the dates to be sorted

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


来源:https://stackoverflow.com/questions/42819415/using-conditional-statements-with-difftime-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!