as.Date wrong date in R

Why as.Date function returning the wrong date in R

If you are converting a string to date, there might be a situation where function as.Date returning the wrong date in R. In that scenario, the key is to specify the format correctly.

 

There is a difference between capital Y and y in the date format used in the function as.Date.

Here is a situation when it is necessary to convert string to date and function as.Date treating it “incorrectly”.

USdate <- c("07/01/2022", "07/02/2022", "07/03/2022")


as.Date(USdate, format = "%m/%d/%y")

#[1] "2020-07-01" "2020-07-02" "2020-07-03"

Looks like as.Date function returning the wrong date in R. The problem is that there should be capital Y in the specified format. It is necessary to get the proper results with as.Date if the year is fully specified.

as.Date(USdate, format = "%m/%d/%Y") 

#[1] "2022-07-01" "2022-07-02" "2022-07-03"

If you want to get the results easier, use the lubridate functions instead.

require(lubridate)

mdy(USdate)

#[1] "2022-07-01" "2022-07-02" "2022-07-03"

In other situations, there might be necessary to use other lubridate functions like ymd, dmy, etc.

 

If you have only part of the year number, it is time to use the small letter y in the format. Here is an example with a two-digit year.

notfullyear <- c("07/01/22", "07/02/22", "07/03/22")

Here are the bad results.

as.Date(notfullyear, format = "%m/%d/%Y") 

#[1] "0022-07-01" "0022-07-02" "0022-07-03"

Here are good results with the conversation of a two-digit year.

as.Date(notfullyear, format = "%m/%d/%y") 

#[1] "2022-07-01" "2022-07-02" "2022-07-03"

As I mentioned earlier the lubridate makes it easier.

require(lubridate)

mdy(notfullyear)

#[1] "2022-07-01" "2022-07-02" "2022-07-03"





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *