4

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!

Paul
  • 8,734
  • 1
  • 26
  • 36
EIBC
  • 43
  • 2
  • How about: `as.Date(as.character(...), format="%Y%m%d")`. – lambruscoAcido Oct 19 '20 at 11:03
  • Btw, if `as.Date(x)` is called with `x` of class `character`, or directly via `as.Date.character(x)`, the second parameter should be `format`. However, if `as.Date(x)` is called with `x` of class `numeric`, or directly via `as.Date.numeric(x)`, the second parameter is `origin`. Because of this behaviour, you should convert your parameter into class `character`. – lambruscoAcido Oct 19 '20 at 11:07

2 Answers2

1

An easy solution would be using the lubridate package.

For example

lubridate::ymd('20130131')
lubridate::ymd(20130131)
lubridate::ymd(dataset2$date)
L Smeets
  • 888
  • 4
  • 17
  • great information on how to work with dates in R can be found here: https://lubridate.tidyverse.org/ – L Smeets Oct 19 '20 at 09:39
0

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"
Paul
  • 8,734
  • 1
  • 26
  • 36
  • This would not work though if the data is numeric (as stated in the question). `as.Date(as.character(20130131) format = "%Y%m%d")`, would work, but is a bit ugly in my opinion. – L Smeets Oct 19 '20 at 09:43
  • Thanks. I've added this to my answer. – Paul Oct 19 '20 at 09:45