-1

I am trying to create an new column in a dataframe titled "Date2" which I will have to loop through previous iterations of the calculation.

The following is the logic.

If ID2 = Previous(ID2) then Previous(Date2) ELSE
Date1 + 60


Example:

ID2     Date 1     Date 2
1001    1/1/2019   3/2/2019
1001    1/1/2019   3/2/2019

In row 1 Date2 is simply Date1+60 since the previous ID2 is different.
In row 2 Date2 is simply the previous Date2 since the previous ID2 is the same as the current.

Code:

OrderedData$Well2BookDate <- 0 # initialize, sometimes better as just `list()`

for(i in 2:nrow(OrderedData)){
  if(OrderedData[i,1]== OrderedData[i-1, 1]){
    # Previous Well 2 Book Date
    OrderedData[i,14 ] <- OrderedData[i-1, 14] 
  } else {
    # Online Date 1 + 60 Days
    OrderedData[i, 14] <- OrderedData[i, 9] + 60
  } 
  }

This code works mostly except the Well 2 Book Date is being output as a number instead of a date. Online Date 1 was already a date class.

Tim Batten
  • 45
  • 7

1 Answers1

1

An option is lag with case_when

library(dplyr)
df1 %>%
     mutate(NewDate = case_when(ID2 == lag(ID2) ~ lag(Date2), TRUE ~ Date1 + 60))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • That won't work since Date2 and NewDate you have are the same variable – Tim Batten Jun 27 '19 at 14:40
  • @TimBatten You haven't provided an example, so it is not clear what your Date2s are – akrun Jun 27 '19 at 14:41
  • ID2 Date 1 Date 2 1001 1/1/2019 3/2/2019 1001 2/1/2019 3/2/2019 – Tim Batten Jun 27 '19 at 14:45
  • Row 1 does Date 1 + 60 since the previous ID2 isn't the same. In row 2 it it simply takes the previous Date 2 since the previous ID2 is the same – Tim Batten Jun 27 '19 at 14:46
  • @TimBatten Please edit your post and update the data. It is difficult to copy/paste from here – akrun Jun 27 '19 at 14:52
  • @TimBatten If you haven't created the 'Date 2', I don't understand `If ID2 = Previous(ID2) then Previous(Date2) ELSE Date1 + 60` – akrun Jun 27 '19 at 15:43
  • row 1 of the frame will automatically do Date+60. Once it has a previous ID to compare to (starting in row 2) then the logic from the previous comment will apply – Tim Batten Jun 27 '19 at 16:33