Search code examples
rdatelubridatedate-conversion

convert numeric column to dates recognized by R


How could I convert this numeric vector of dates into the date format that R can recognize?

date <- c(29101958L, 10121957L, 27091953L, 23021960L, 
           6031967L, 10011968L, 10101958L, 9101992)

I would like an output like:

'1958-10-29', '1957-12-10', '1953-09-27', '1960-02-23', '1967-03-06', '1968-01-10', '1958-10-10', '1992-10-09'

Then I would like to calculate the age by making the difference from 2016-12-31 with the dates of the vector.

I appreciate any help.


Solution

  • We can use dmy from lubridate

    library(lubridate)
    newdate <- dmy(date)
    
    newdate
    #[1] "1958-10-29" "1957-12-10" "1953-09-27" "1960-02-23" "1967-03-06" "1968-01-10" "1958-10-10" "1992-10-09"
    

    and get the difference between the new date in years

    as.integer(difftime(as.Date('2016-12-31'), newdate, units = 'days')/365)
    #[1] 58 59 63 56 49 49 58 24