Search code examples
rdatestrptime

R, strptime(), %b, trying to convert character to date format


Hi i have some troubles concerning the strptime() function, i have character data like:

data2[,1]

24-feb-15
26-ene-15
29-dic-14

i try to use srtptime() :

strptime(data2[,1], "%d-%b-%y")

but unfortunately it only works for 24-feb-15, i guess its because the other months are spanish abbreviated, so R doesn't recognize them, i have a lot of observations so i want to find a way to do it without changing manually the name of the months. Thanks for your help.

JDaniel


Solution

  • strptime will recognize abbreviated names in the current locale. You can change your current locale to spanish, transform your dates, then change it back to the original setting:

    #save your current locale
    original_locale<-Sys.getlocale(category = "LC_TIME")
    
    #change it to spanish
    Sys.setlocale(category = "LC_TIME", locale = "es_ES.UTF-8")
    
    #transform your dates
    data<-c("24-feb-15","26-ene-15","29-dic-14")
    strptime(data,format="%d-%b-%y")
    
    #[1] "2015-02-24 GMT" "2015-01-26 GMT" "2014-12-29 GMT"
    
    #change it back to the original setting
    Sys.setlocale(category = "LC_TIME", locale = original_locale)