Cheng
Cheng

Reputation: 193

how to read the date format in R language

I try to read the date like 03-Nov-11, and I use the code as followed:

s<-c("03-Nov-13")
s1<-as.Date(s,"%d-%b-%y")

but s1 is NA.

Upvotes: 2

Views: 576

Answers (1)

Dominic Comtois
Dominic Comtois

Reputation: 10411

The %b seems to be problematic indeed. I've had luck with those though:

s1 <- "03-11-13"

as.POSIXct(s1, format = "%d-%m-%y")
# [1] "2013-11-03 EDT"

s2 <- "03-NOVEMBRE-13" # Note that I have Fr locale, hence the ending in "BRE"

as.POSIXct(s2, format = "%d-%B-%y")
# [1] "2013-11-03 EDT"

as.POSIXct(s2, format = "%d-%b-%y")
# [1] "2013-11-03 EDT"

However, the abbreviated version doesn't seem to work at all on Windows:

s3 <- "03-NOV-13"
as.POSIXct(s3, format = "%d-%B-%y")
# [1] NA

as.POSIXct(s3, format = "%d-%b-%y")
# [1] NA

EDIT

After trying on Linux, the %b does what is expected!

as.POSIXct(s3, format="%d-%b-%y")
# [1] "2013-11-03 PDT"

as.POSIXct(s3, format="%d-%B-%y")
# [1] "2013-11-03 PDT"

EDIT 2

Filed a bug report; See https://bugs.r-project.org/bugzilla/show_bug.cgi?id=16301

EDIT 3

On my end I was mistaken -- my locale's months abbreviations are given by:

z <- seq.Date(as.Date('2015-01-01'), by='month', len = 12)
format(z, "%d-%b-%y")

#  [1] "01-janv.-15" "01-févr.-15" "01-mars-15"  "01-avr.-15"  "01-mai-15"
#  [6] "01-juin-15"  "01-juil.-15" "01-août-15"  "01-sept.-15" "01-oct.-15"
# [11] "01-nov.-15"  "01-déc.-15"

So using "nov.", "NOV.", "NOVEMBRE" or "novembre" works fine.

Upvotes: 3

Related Questions