-2

I'm trying to convert a factor to date but I keep getting NA values. The format of the date value I have as date is like: dd-mmm-yy. For example with the following code:

dates <- c('21-Feb-16', '22-Feb-16', '23-Feb-16')
valx <- c(100,200,300)
df.dates <- data.frame(dates, valx)

I have tried some of the examples in here, but when I try to convert the date I get an NA value

as.Date(df.dates$dates, format = "%d/%m/%Y")
[1] NA NA NA

My intention is to do a time line chart, but I cannot figure out how to convert the date properly

Community
  • 1
  • 1
Selrac
  • 2,203
  • 9
  • 41
  • 84

1 Answers1

2

You have the wrong format string. Instead, try:

as.Date(df.dates$dates, format = "%d-%b-%y")
[1] "2016-02-21" "2016-02-22" "2016-02-23"

Your original format used / but your data has -
Your original format had %Y (which is for 4 digit years)
Your original format had %mmm but for 3 letter month abbreviations you need %b
The formats are documented with strptime

G5W
  • 36,531
  • 10
  • 47
  • 80