Sharif Amlani
Sharif Amlani

Reputation: 1278

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.

Upvotes: 2

Views: 1006

Answers (3)

DeduciveR
DeduciveR

Reputation: 1702

using lubridate, it's even easier:

x = c("4252001", "5092001", "4242001", "5092001", "5192001", "6292001", "10242001")

library(lubridate)

mdy(as.numeric(x))

[1] "2001-04-25" "2001-05-09" "2001-04-24" "2001-05-09" "2001-05-19" "2001-06-29" "2001-10-24"

Upvotes: 0

Onyambu
Onyambu

Reputation: 79188

just do:

x = c("4252001", "5092001", "4242001", "5092001", "5192001", "6292001", "10242001") 

as.Date(sprintf('%08d',as.numeric(x)),'%m%d%Y')

[1] "2001-04-25" "2001-05-09" "2001-04-24" "2001-05-09" "2001-05-19" "2001-06-29" "2001-10-24"

Upvotes: 0

dww
dww

Reputation: 31452

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')

Upvotes: 1

Related Questions