0

Please help me to transform characters to date format

as.date and strptime don't work...

c <- data.frame(id = c('1', '2', '3', '4'), Date = c("01-Feb-16","03-May-15","24-Oct-14","20-Oct-12"))
c$Date <- as.character(c$Date)
str(c)

then I'm trying use code:

c$Date <- as.Date(c$Date, format = "%d-%b-%y")

or

c$Date <- strptime(c$Date, '%d-%b-%y')

And I have received NA

Denis
  • 159
  • 2
  • 4
  • 17
  • The two methods you mentioned both return the correct Date vector for me, how do you mean "And i have received `NA`"? – robbertjan94 Jun 04 '17 at 13:59
  • 4
    It works for me too. Perhaps your locale does not by default recognise the abbreviations 'Jan', 'Feb', etc??? – Andrew Gustar Jun 04 '17 at 14:01
  • ` $ Date: POSIXlt, format: NA NA NA ...` – Denis Jun 04 '17 at 14:13
  • 1
    First it didn't work for me either, as my local language is not English, but here is an answer I have found useful: https://stackoverflow.com/a/18380929/7306168 – Bea Jun 04 '17 at 14:18

1 Answers1

1

Your date is in the german format with english monthnames. Try this prior to your code:

c <- data.frame(lapply(c, function(y) {
y <- gsub("May", "Mai", y); y
y <- gsub("Oct", "Okt", y); y
}))

c$Date1 <- as.Date(c$Date, format = "%d-%b-%y")
c$Date2 <- strptime(c$Date, '%d-%b-%y')
c

# id      Date      Date1      Date2
# 1  1 01-Feb-16 2016-02-01 2016-02-01
# 2  2 03-Mai-15 2015-05-03 2015-05-03
# 3  3 24-Okt-14 2014-10-24 2014-10-24
# 4  4 20-Okt-12 2012-10-20 2012-10-20
jay.sf
  • 60,139
  • 8
  • 53
  • 110