I\'m working with the London crime dataset which contains dates in an integer format. I melted them and now they have become factor
s.
For example, \"
One possibility is to use lubridate
ss <- factor("X200801")
library(lubridate)
ymd(paste(sub("X", "", ss), "01", sep = ""))
#[1] "2008-01-01"
It can be compactly changed with as.yearmon
library(zoo)
as.Date(as.yearmon("X200801", "X%Y%m"))
#[1] "2008-01-01"
You can use parse_datetime from the readr package:
testdate <- factor("X200801")
parse_datetime(as.character(testdate), format = 'X%Y%M')
I wouldn't recommend using MM/DD/YYY in R. Keeping things in the ISO 8601 format is preferable.
Using base R we can add the date component using paste0
convert to date object using appropriate format
.
as.Date(paste0("X200801", "01"), format = "X%Y%m%d")
#[1] "2008-01-01"
Using anytime
:
test=as.factor("X200801")
library(anytime)
anydate((gsub("X","",test)))
[1] "2008-01-01"
As suggested by @akrun we can simply supply a format that will be used within our environment with addFormats
and use anydate
to convert to date:
addFormats("X%Y%m")
anydate("X200801")