Search code examples
rdatedplyrlubridate

How to print a date when the input is number of days since 01-01-60?


I received a set of dates, but it turns out that time is reported in days since 01-01-1960 in this specific data set.

  D_INDDTO
1    20758
2    20856
3    21062
4    19740
5    21222
6    21203

The specific date of interest for Patient 1 is 20758 days since 01-01-60

I want to create a new covariate u$date containing the specific date of interest i d%m%y%. I tried

library(tidyverse) 
u %>% mutate(date=as.date(D_INDDTO,origin="1960-01-01")

But that did not solve it.

u <- structure(list(D_INDDTO = c(20758, 20856, 21062, 19740, 21222, 
21203, 20976, 20895, 18656, 18746)), row.names = c(NA, 10L), class = "data.frame")

Solution

  • Try this:

    #Code 1
    u %>% mutate(date=as.Date("1960-01-01")+D_INDDTO)
    

    Output:

       D_INDDTO       date
    1     20758 2016-10-31
    2     20856 2017-02-06
    3     21062 2017-08-31
    4     19740 2014-01-17
    5     21222 2018-02-07
    6     21203 2018-01-19
    7     20976 2017-06-06
    8     20895 2017-03-17
    9     18656 2011-01-29
    10    18746 2011-04-29
    

    Or this:

    #Code 2
    u %>% mutate(date=as.Date(D_INDDTO,origin="1960-01-01"))
    

    Output:

       D_INDDTO       date
    1     20758 2016-10-31
    2     20856 2017-02-06
    3     21062 2017-08-31
    4     19740 2014-01-17
    5     21222 2018-02-07
    6     21203 2018-01-19
    7     20976 2017-06-06
    8     20895 2017-03-17
    9     18656 2011-01-29
    10    18746 2011-04-29
    

    Or this:

    #Code 3
    u %>% mutate(date=format(as.Date(D_INDDTO,origin="1960-01-01"),'%d%m%y'))
    

    Output:

       D_INDDTO   date
    1     20758 311016
    2     20856 060217
    3     21062 310817
    4     19740 170114
    5     21222 070218
    6     21203 190118
    7     20976 060617
    8     20895 170317
    9     18656 290111
    10    18746 290411
    

    If more customization is required:

    #Code 4
    u %>% mutate(date=format(as.Date(D_INDDTO,origin="1960-01-01"),'%d-%m-%Y'))
    

    Output:

       D_INDDTO       date
    1     20758 31-10-2016
    2     20856 06-02-2017
    3     21062 31-08-2017
    4     19740 17-01-2014
    5     21222 07-02-2018
    6     21203 19-01-2018
    7     20976 06-06-2017
    8     20895 17-03-2017
    9     18656 29-01-2011
    10    18746 29-04-2011