Search code examples
rdatenumericmerging-data

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


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!


Solution

  • An easy solution would be using the lubridate package.

    For example

    lubridate::ymd('20130131')
    lubridate::ymd(20130131)
    lubridate::ymd(dataset2$date)