changing numeric data variable into date format in R to merge two datasets

735 views Asked by At

I am trying to merge two datasets where date and an id variable are the two common identifiers.

In one dataset the date variable is of character type and looked like this: '31jan2013'. We thus used the as.Date function to change it into date format (as.Date(dataset1$date, format = "%d%b%Y") creating a new date column that shows the date like this: '2013-01-31'.

The issue comes in when we want to change the other date variable from our second dataset. In dataset2 the date variable is of numeric nature and looks like this: '20130131'. We again tried to use the as.Date function (as.Date.numeric(dataset2$date["datadate"], "%Y%m%d") however we get this error:

**Error in charToDate(x) : 
  character string is not in a standard unambiguous format**

Any help is highly appreciated!

2

There are 2 answers

1
L Smeets On BEST ANSWER

An easy solution would be using the lubridate package.

For example

lubridate::ymd('20130131')
lubridate::ymd(20130131)
lubridate::ymd(dataset2$date)
2
Paul On

The date format can be specified with the format parameter.

as.Date('20130131', format = "%Y%m%d")
[1] "2013-01-31"

If the data is numeric

as.Date(as.character(20130131), format = "%Y%m%d")
[1] "2013-01-31"