Unable to convert this Character type to a proper Date type in R

1.5k views Asked by At

I have a data set that has a column for dates (emp2$hiredate) which is in char format. While converting it to Date, I'm getting the following error :

> date1 <- emp2$hiredate[2]

> str(date1)
chr "20FEB1981"

> as.POSIXct(date1)
Error in as.POSIXlt.character(x, tz, ...) : 
character string is not in a standard unambiguous format

How do I solve this problem?

1

There are 1 answers

0
Rich Scriven On BEST ANSWER

R doesn't automatically know the format of the date in the string. You need to use the format argument to tell it how to process the string.

You can use as.Date to create a date

as.Date("20FEB1981", "%d%b%Y")
# [1] "1981-02-20"

Or use as.POSIXct with the format option to create a date-time

as.POSIXct("20FEB1981", format = "%d%b%Y")
# [1] "1981-02-20 PST"
  • %d means the day of the month in decimal form
  • %b means that the month is not in numeric form, but rather an abbreviated name
  • %Y (capitalized) means the year is in century form (all four numbers)