hn.phuong
hn.phuong

Reputation: 835

Convert a string to Date by as.Date function

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

Answers (3)

Julius Vainora
Julius Vainora

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

tyluRp
tyluRp

Reputation: 4768

One solution with lubridate:

lubridate::ymd(a)

# [1] "2017-08-14"

class(lubridate::ymd(a))

# [1] "Date"

Upvotes: 2

akrun
akrun

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

Related Questions