Reputation: 835
I have my string formatted as: 20170814 and wanted to convert to date by as.Date function but keep producing me 'NA". This is my function:
a<-"20170814"
as.Date(a,"%y-%m/%d")
Can you please give me some help Thanks
Upvotes: 1
Views: 839
Reputation: 48241
You want to use
as.Date(a, "%Y%m%d")
# [1] "2017-08-14"
because "%Y%m%d"
is the description of the format of the character that you provide, which does not include /
or -
. Also, Y
is needed when the year consists of 4 digits rather than 2.
Upvotes: 1
Reputation: 4768
One solution with lubridate
:
lubridate::ymd(a)
# [1] "2017-08-14"
class(lubridate::ymd(a))
# [1] "Date"
Upvotes: 2
Reputation: 887571
The format is %Y%m%d
and there is no -
as.Date(a,"%Y%m%d")
#[1] "2017-08-14"
Another option is anytime
which can parse most of the formats and convert it to Date
class
anytime::anydate(a)
#[1] "2017-08-14"
class(anytime::anydate(a))
#[1] "Date"
Upvotes: 1