I am hoping to create a new variable in datatable that adds a column telling me the number of days since the opposite (or other event occured).
The dataset I have looks like the following:
date event id obs_since_event_1 obs_since_event_2
2000-07-06 2 1 NA NA
2000-07-07 1 1 NA 1
2000-07-09 0 1 1 2
2000-07-10 0 1 2 3
2000-07-15 2 1 3 4
2000-07-16 1 1 4 1
2000-07-20 0 1 1 2
2000-07-21 1 1 2 3
2000-07-06 1 2 NA NA
2000-07-07 2 2 1 NA
2000-07-15 0 2 2 1
2000-07-16 0 2 3 2
2000-07-17 2 2 4 3
2000-07-18 1 2 5 1
And I am hoping to add a column called days_since_opposite. which records number of days since the opposite event occurred (the opposite events being 1 and 2). I already have the number of days since either an event 1 or 2 occurred. Now I need to work out an if statement that works in datatables that will provide me with the corresponding values in the final column.
date event id obs_since_event_1 obs_since_event_2 days_since_opposite
2000-07-06 2 1 NA NA NA
2000-07-07 1 1 NA 1 NA
2000-07-09 0 1 1 2 NA
2000-07-10 0 1 2 3 NA
2000-07-15 2 1 3 4 3
2000-07-16 1 1 4 1 1
2000-07-20 0 1 1 2 NA
2000-07-21 1 1 2 3 3
I hope this is clear. I also have different ids to reckon with but not sure if it impacts the results.
I tried something along the following lines but it did not work:
data[,days_since_opposite:=ifelse(event==1,obs_since_event_2,ifelse(event==2,obs_since_event_1,0)),]
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire