How to convert integer to date format in R?

1234 views r
0

Sorry, I have basic question about R. I'm trying to convert integer data from my data frame in R, to date format.

The data is under column named svcg_cycle within orig_svcg_filtered data frame.

The original data looking something like 200502, 200503, and so forth, and I expect to turn it into yyyy-mm-dd format.

I am trying to use this code:

as.Date(orig_svcg_filtered$svcg_cycle, origin = "2000-01-01")

but the output is not something that I expected:

[1] "2548-12-15" "2548-12-15" "2548-12-15" "2548-12-15" "2548-12-15" 

while it is supposed to be 2005-02-01, 2005-03-01, and so forth.

Could anybody please help me to solve this basic thing?.

Thank you so much

answered question

1 Answer

3

If you have

x <- c(200502, 200503)

Then

as.Date(x, origin = "2000-01-01")

tells R you want the days 200,502 and 200,503 days after 2000-01-01. From help("as.Date"):

as.Date will accept numeric data (the number of days since an epoch), but only if origin is supplied.

So, integer data gives days after the origin supplied, not some sort of numeric code for the dates like 200502 for "2005-02-01".

What you want is

as.Date(paste(substr(x, 1, 4), substr(x, 5, 6), "01", sep = "-"))

# [1] "2005-02-01" "2005-03-01"

The

paste(substr(x, 1, 4), substr(x, 5, 6), "01", sep = "-")

part takes your integers and creates strings like

# [1] "2005-02-01" "2005-03-01"

Then as.Date() knows how to deal with them.

You could alternatively do something like

as.Date(paste0(x, "01"), format = "%Y%m%d")

# [1] "2005-02-01" "2005-03-01"

This just pastes on an "01" to each element (for the day), converts to character, and tells as.Date() what format to read the date into. (See help("as.Date") and help("strptime")).

posted this

Have an answer?

JD

Please login first before posting an answer.