Search code examples
rdatetime-seriescharacterrecode

How to add a - to a date in r?


I have dates in my data set that are formatted in the following way:

"4252001" "5092001" "4242001" "5092001" "5192001" "6292001" "10242001"

I want to add a dash (-) in between them, so they look like this:

"4-25-2001" "5-09-2001" "4-24-2001" "5-09-2001" "5-19-2001" "6-29-2001" "10-24-2001"

Then I want to convert them into time series data in r.

For the life of me, I cannot figure out how to add the dash to these dates.

Also, depending on the month, some dates have 7 or 8 characters. In trying to figure out how to make them into dates, this was an important consideration that I wanted to pass along to anyone trying to help.


Solution

  • You can use

    x = c("4252001", "5092001", "4242001", "5092001", "5192001", "6292001", "10242001")    
    y = sub('(\\d{2})(\\d{4})$', '-\\1-\\2', x)
    ##[1] "4-25-2001"  "5-09-2001"  "4-24-2001"  "5-09-2001"  "5-19-2001" 
    ##[6] "6-29-2001"  "10-24-2001"
    

    Then to convert to date

    as.Date(y, format = '%m-%d-%Y')