lundi 12 juillet 2021

In R how to calculate if Date is earlier then date X?

I got a DF with a date column in it. I want to check if the date in the column is after or before 1st of January 2020. Create a new column and if the previous columns date is before then insert 1st of January 2020 if not then insert previous columns date.

Date is in format YYYY-MM-DD

 
Beginning    End
2020-12-31  2021-01-12
2018-01-02  2020-03-10
2019-04-12  2020-12-04
2020-10-15  2021-03-27

I want:

 
Beginning      End        Beginning_2
2020-12-31  2021-01-12     2020-12-31
2018-01-02  2020-03-10     2020-01-01 
2019-04-12  2020-12-04     2020-01-01 
2020-10-15  2021-03-27     2020-10-15

The code i wrote is: DF$Beginning_2 <- ifelse("2020-01-01" > DF$Beginning,"2020-01-01", DF$Beginning)

I'm getting this

 
Beginning      End        Beginning_2
2020-12-31  2021-01-12     18554 
2018-01-02  2020-03-10     2020-01-01 
2019-04-12  2020-12-04     2020-01-01  
2020-10-15  2021-03-27     18453 

My code works half way. It turns the format in to char. I need it to stay as date. I tried butting as date all over the code but nothing much changed. The biggest change was that greater then 2020-01-01 dates were NA instead of "18554".

How to fix my code?

Thank you

Aucun commentaire:

Enregistrer un commentaire