Converting Date formats in R [closed]
Good practice is to store date in R as YYYY-MM-DD, and your strings already seem to be at the good format, but :
The format you're passing to as.Date
must describe what the strings contain, not what you're expecting as an output.
"%d/%b/%Y"
stands for "day as a number (0-31) slash abbreviated month slash 4-digit year", and your strings format are "4-digit year - month as a number - day as a number".
If you want to format the date, you need to call format
:
> date <- "2016-01-01"
> date <- as.Date(date, format = "%Y-%m-%d")
> date
[1] "2016-01-01"
> format(date, "%d/%b/%Y")
[1] "01/jan/2016"
To obtain your required format i.e., 2016-month-day , you can use format
function once you have converted vector of strings to Date
type.
I hope below code snippet clears your doubt.
> d = c("2016-02-08","2016-02-18","2015-02-08","2016-02-02")
> class(d)
[1] "character"
> d = as.Date(d)
> class(d)
[1] "Date"
> d = format(d,"%Y-%b-%d")
> d
[1] "2016-Feb-08" "2016-Feb-18" "2015-Feb-08" "2016-Feb-02"
Format function converts the date type objects into the required format. Refer to this link for more information on date type formatting.
If you just want to render your dates in this format, then use format
:
x <- as.Date("2016-01-01")
format(x, "%Y %b %a %d")
[1] "2016 Jan Fri 01"
There is a separation of concerns here. If you already have your date information stored in R as date types, then you need not change anything internally to extract further information from those dates.
Demo
You would use as.Date()
to convert between dates saved as character and Date
objects.
If you want to change the format of a Date
object, you can use format()
.
You have specified "2016-month-day"
as the desired format of the dates in the question, but in the code you provide you are using "%d/%b/%Y"
. The way this works is: the %
indicates that the next character will be a conversion specification, everything else (e.g. (-
or /
) will be used for finding / adding delimiter to the date representation. (see ?strptime
for details).
So in your case, just use
dates <- format(dli$Dates, format = "%Y-%b-%d")
to get the result specified in the text of the question:
[1] "2016-Jan-01" "2016-Jan-02" "2016-Jan-03" "2016-Jan-04" "2016-Jan-05"
or this:
dates <- format(dli$Dates, format = "%Y/%b/%d")
to get what you have used in the code snipped:
[1] "2016/Jan/01" "2016/Jan/02" "2016/Jan/03" "2016/Jan/04" "2016/Jan/05"