21

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?

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293

4 Answers4

19

With recent versions of R, you have to supply the origin :

as.Date(x = integer(0), origin = "1970-01-01")
PAC
  • 5,178
  • 8
  • 38
  • 62
12

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")
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • In my case : `> as.Date(x = integer(0))` returns an error : `Error in as.Date.numeric(x = integer(0)) : 'origin' must be supplied`. I've to supply origin : `as.Date(x = integer(0), origin = "1970-01-01")` works ! – PAC Apr 03 '17 at 10:19
  • 1
    It's not the method I demonstrated, which continues to succeed. The behavior of `as.Date(integer())` appears to have changed. It now returns the error you demonstrated. I'm unable to find an entry in the NEWS file that explains that change. – IRTFM Apr 03 '17 at 15:17
8

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.

Dylan S.
  • 359
  • 4
  • 15
2

This appears to work and saves a few keystrokes relative to some of the other answers:

> as.Date(character(0))
Date of length 0

gbrunick
  • 61
  • 2