0

I have two different dataframe with different date formats

date1<-c('2001-01-30', '2001-02-25')

data2 <- c('200101','200102')

I want to convert these dates in the same format so I can merge my two different dataframes by date.

The frequency is on a monthly basis.

Can someone help me with this task?

msh855
  • 1,493
  • 1
  • 15
  • 36

1 Answers1

0

EDIT(Caution): This is not best practice and the use of standard parsers is recommended. However, different requirements may come up and therefore this answer simply shows how to get the expected format in the OP and in a comment from OP.

We could use:

paste0(substring(data2,nchar(data2)-1,nchar(data2)),"/",substring(data2,1,4))
#[1] "01/2001" "02/2001"

To get the reverse:

paste0(substring(data2,1,4),"-",substring(data2,nchar(data2)-1,nchar(data2)))
[1] "2001-01" "2001-02
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    You should never ever use regexps on dates. The custom date parsers know Feb 30 and May 32 and a 14th month do not exist, your regexp never will. – Dirk Eddelbuettel Apr 13 '19 at 12:23
  • Thanks for the information, didn't know that. @Dirk Eddelbuettel could you further elaborate the Feb 30 and May 32 part? – NelsonGon Apr 13 '19 at 12:25
  • what if I want in this format `2001-01` ? – msh855 Apr 13 '19 at 13:28
  • @msh885 `paste0(substring(data2,1,4),"-",substring(data2,nchar(data2)-1,nchar(data2)))`. However maybe using standard parsers is better. I was just answering the question. – NelsonGon Apr 13 '19 at 13:35