I have the following data. df is my starting point. df2 is what I want to achieve.
df
"ID" "event" "time" "group"
1 FALSE 1990-01-01 1
2 FALSE 1990-01-02 1
3 FALSE 1990-01-03 1
4 TRUE 1990-01-04 1
5 FALSE 1990-01-02 2
6 TRUE 1990-01-03 2
7 FALSE 1990-01-03 3
df2 (what I need)
"ID" "event" "time" "group" distance
1 FALSE 1990-01-01 1 3
2 FALSE 1990-01-02 1 2
3 FALSE 1990-01-03 1 1
4 TRUE 1990-01-04 1 0
5 FALSE 1990-01-02 2 1
6 TRUE 1990-01-03 2 0
7 FALSE 1990-01-03 3 NA
I need the date-difference (distance column) between any observation within a group to the observation which fulfills the event=TRUE condition. If there is no event occuring in the group a NA should be put in place of the distance indicator.