Reputation: 40543
Is it possible to create an empty vector of dates in r?
I can create an empty vector of integers, doubles, logicals etc:
> integer()
integer(0)
> double()
numeric(0)
> logical()
logical(0)
> length(integer())
[1] 0
but this meme doesn't work for dates, as date()
returns the current system date and time. So, how would I create an emtpy vector of dates?
Upvotes: 23
Views: 19209
Reputation: 61
This appears to work and saves a few keystrokes relative to some of the other answers:
> as.Date(character(0))
Date of length 0
Upvotes: 2
Reputation: 389
Using the lubridate package and deciding what your intended format will be (eg. yyyy/mm/dd) you can use:
lubridate::ymd()
# or
lubridate::mdy()
etc.
Upvotes: 9
Reputation: 5366
With recent versions of R, you have to supply the origin :
as.Date(x = integer(0), origin = "1970-01-01")
Upvotes: 20
Reputation: 263421
Just add a class attribute to a length-0 interger and it's a Date (at least it will appear to be one if you extend it with values that are sensible when interpreted as R-Dates):
> x <- integer(0)
> x
integer(0)
> class(x) <- "Date"
> x
character(0)
> class(x)
[1] "Date"
> y <- c(x, 1400)
> y
[1] "1973-11-01"
The output from as.Date
happens to be a character value so the first call is a bit misleading.
> as.Date(integer())
character(0)
> str( as.Date(integer()) )
Class 'Date' num(0)
> dput( as.Date(integer()) )
structure(numeric(0), class = "Date")
Upvotes: 12