Search code examples
rdatedatatabledata-cleaning

R how get a date from variable in character


I have data that has dates in a character format, as "JAN2005","FEB2005","MAR2005", such as :

Test <- data.table(c("JAN2005","FEB2005","MAR2005","APR2005"),c(436.6,543.1,417.3,687.4))

Is there a simple way to get the date in an actual date format ?


Solution

  • We can use as.yearmon from zoo

    library(data.table)
    Test[, V1 := as.Date(zoo::as.yearmon(V1))]
    

    Or convert to a proper 'Date' by pasteing the day as well and then use as.Date

    Test[, V1 := as.Date(paste0(V1, '01'), "%b%Y%d")]
    

    If the locale is different from English, change it to match the 'month' as it is in English

    Sys.setlocale("LC_ALL","English")