Ops Data
Ops Data

Reputation: 1

Date format changes

I am just preparing the some table like cols<- c("Metrics",as.Date(Sys.Date()-8,origin="1899-12-30"),as.Date(Sys.Date()-1,origin="1899-12-30")) , and I am not getting the expected output. Any one please help.
Output : "Metrics" "17927" "17934"

cols<- c("Metrics",as.Date(Sys.Date()-8,origin="1899-12-30"),as.Date(Sys.Date()-1,origin="1899-12-30"))

cols<- c("Metrics",as.Date(Sys.Date()-8,origin="1899-12- 
30"),as.Date(Sys.Date()-1,origin="1899-12-30"))

Expected Output:

"Metrics" "2019-01-31"   "2019-02-07" 

Upvotes: 0

Views: 35

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269624

1) character output If you are looking for a character vector as the result then convert the Date class components to character. Also note that the as.Date shown in the question is not needed since Sys.Date() and offsets from it are already of Date class. Further note that if Sys.Date() were called twice right at midnight it is possible that the two calls might occur on different days. To avoid this possibility we create a today variable so that it only has to be called once.

today <- Sys.Date()
cols <- c("Metrics", as.character(today-8), as.character(today-1))
cols
## [1] "Metrics"    "2019-01-31" "2019-02-07"

1a) This could be made even shorter like this.

cols <- c("Metrics", as.character(Sys.Date() - c(8, 1)))
cols
## [1] "Metrics"    "2019-01-31" "2019-02-07"

2) list output Alternately if what you want is a list with one character component and two Date components then:

today <- Sys.Date()
L <- list("Metrics", today - 8, today - 1)
L

giving:

[[1]]
[1] "Metrics"

[[2]]
[1] "2019-01-31"

[[3]]
[1] "2019-02-07"

If we already had L and wanted a character vector then we could further convert it like this:

sapply(L, as.character)
## [1] "Metrics"    "2019-01-31" "2019-02-07"

Upvotes: 1

Related Questions