I want to calculate the relationship length per customer ID, however the relationshiplength should be the same for every purchase using the ID. This length is either defection date - first date (if defection is 1) OR 2202-02-11 - first date (if defection = 0). Now it generates for every entry seperately, instead of the ID.
## Relationship length
dataset$relationship_length <- if_else(dataset$defected == 1, as.numeric(dataset$defection_date - dataset$first_donation_date),
as.numeric(as.Date("2022-02-11") - dataset$first_donation_date))
Below one can see the current dataset and the desired outcome.
ID first_donation_date date_of_donation defected defection_date relationship_length
1 2014-01-13 2014-01-13 0 NA 2951
1 2014-01-13 2014-04-14 0 NA 2951
1 2014-01-13 2014-08-13 0 NA 2951
1 2014-01-13 2014-09-12 0 NA 2951
1 2014-01-13 2014-11-12 0 NA 2951
1 2014-01-13 2015-02-13 0 NA 2951
1 2014-01-13 2017-02-14 1 2017-02-14 1128
1 2014-01-13 2018-12-13 1 2018-12-13 1795
2 2013-12-02 2013-12-02 0 NA 2993
2 2013-12-02 2014-05-02 0 NA 2993
The desired outcome is that all relationship_length for ID 1 are 1128 (the first defected=1). And for ID 2 it is 2993, as the customer never defected.
I hope this explains my question and i look forward to the answers