0

Following is part of my data:

       Date        Elev Temp.C 
1 02 January 2010  200   14.7
2 02 January 2010  300    5
3 02 January 2010  500    -2
4 02 January 2010 1000   -9.8
5 02 January 2010 2000   -7.1

I wanted to change the format of the date in to 2010-01-01 or "%Y-%m-%d". Class of data is character and I tried as follows:

data$Date<-as.Date(data$Date,format="%d%B%Y")

data$Date<-as.Date(data[["Date"]],"%d%B%Y")

data$Date<-strptime(data$Date,"%d%B%Y")

All of the above trials are displaying <NA>in the Date column. I have another data file with date format of "%m/%d/%Y", it worked fine with strptime, but for the above data set it is not working. Any idea?

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
G1124E
  • 407
  • 1
  • 10
  • 20

1 Answers1

1

The problem is related to your locale. If you look at ?strptime, you will see:

 ‘%B’ Full month name in the current locale.  (Also matches
      abbreviated name on input.)

This means, %B is sensitive to your locale. Have a look at ?locales if you are unsure what a locale is. When I asked you about the output of Sys.getlocale("LC_TIME"), you said you got "English_United States.1252". Now let's first change your locale:

Sys.setlocale("LC_TIME", "C")

Then do:

as.Date("02 January 2010", "%d %B %Y")
# [1] "2010-01-02"

Note, since there is an empty space between "02", "January" and "2010", you need to leave an empty space between %d, %B, %Y. So, don't use "%d%B%Y" as put in your post, but use "%d %B %Y".

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248