Reputation: 23
I'm having trouble formatting a list of dates in R. The conventional methods of formatting in R such as as.Date or as.POSIXct don't seem to be working.
I have dates in the format: 1012015
using
as.POSIXct(as.character(data$Start_Date), format = "%m%d%Y")
does not give me an error, but my date returns
"0015-10-12"
because the month is not a two digit number.
Is there a way to change this into the correct date format?F
Upvotes: 0
Views: 120
Reputation: 269852
This uses only base R. The %08d
specifies a number to be formatted into 8 characters with 0 fill giving in this case "01012015"
.
as.POSIXct(sprintf("%08d", 1012015), format = "%m%d%Y")
## [1] "2015-01-01 EST"
Note that if you don't have any hours/minutes/seconds it would be less error prone to use "Date"
class since then the possibility of subtle time zone errors is eliminated.
as.Date(sprintf("%08d", 1012015), format = "%m%d%Y")
## [1] "2015-01-01"
Upvotes: 0
Reputation: 42564
The lubridate
package can help with this:
lubridate::mdy(1012015)
[1] "2015-01-01"
The format looks ambiguous but the OP gave two hints:
format = "%m%d%Y"
in his own attempt, andUpvotes: 3