Turning an actual date into an integer value in R
13,598
Solution 1
Simply format the Date in that way, then call as.integer
on the result.
R> as.integer(format(Sys.Date(), "%Y%m%d"))
[1] 20151008
If your date isn't a Date, and is a character string: either convert it to a Date first, or remove the "-"
before calling as.integer
.
R> dateString <- "2014-12-31"
R> as.integer(format(as.Date(dateString), "%Y%m%d"))
[1] 20141231
R> as.integer(gsub("-", "", dateString))
[1] 20141231
Solution 2
Or if you already have character dates:
a <- "2015-03-15"
as.integer(gsub(pattern = "-", replacement="", x = a))
#[1] 20150315
Related videos on Youtube
Author by
Qaribbean
Updated on October 16, 2022Comments
-
Qaribbean over 1 year
Using R, I want to be able to turn a date in format "2014-12-31" to an integer of 20141231, for the purpose of creating a serial number.
My aim is simply to be able to complete the REVERSE of this user question (Turning an integer string date into an actual date).
Appreciate any help provided.
-
Qaribbean over 8 yearsThank you for a swift reply @joshua-ulrich. In attempting to use this solution I receive the following error:
> as.integer(format(testdate, "%Y%m%d")) Error in format.default(testdate, "%Y%m%d") : invalid 'trim' argument
-
Roland over 8 years@Qaribbean Your "date" is not a
Date
variable. Either useas.Date
or the suggestion in the other answer. -
Joshua Ulrich over 8 years@Qaribbean: You said you had a date, so I assumed it was a Date object. Apparently, it's just a character string.
-
Qaribbean over 8 years@joshua-ulrich My apologies for not clarifying.
-
Qaribbean over 8 years@joshua-ulrich Thank you for that updated answer, this is also helpful!