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
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
 
    
    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"
 
    
    One solution with lubridate:
lubridate::ymd(a)
# [1] "2017-08-14"
class(lubridate::ymd(a))
# [1] "Date"
 
    
    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.
