2

How can I define a blank vector which can handle dates?

For example:

# this doesn't work ... produces error message
test_vct <- vector(mode = "Date")

# this works but
test_vct <- vector(mode = "double")
dte_current_upper <- as.Date("2014-12-31")


test_vct <- c(test_vct, as.Date("2014-12-31"))
# this displays as 16435
test_vct

# a vector of dates is possible but how to define a blank vector ?
vct_dates <- c(as.Date("2014-12-31"), as.Date("2013-12-31"))
class(vct_dates)
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
markthekoala
  • 1,065
  • 1
  • 11
  • 24
  • Sorry, but I don't understand what you are trying to do. You want something like `xts::xts(order.by=Sys.Date()+0:10)`? –  Feb 04 '16 at 01:03

3 Answers3

4

You can use:

as.Date(NA)

Here's a test:

> c(as.Date(NA), 0)
[1] NA           "1970-01-01"

Can also construct an all-NA vector:

as.Date(rep(NA, 10))
IRTFM
  • 258,963
  • 21
  • 364
  • 487
3

You can use structure() with integer(). This creates an empty vector of mode integer but class Date, which can later be used in calculations. You can assign to x using character vectors.

x <- structure(integer(), class = "Date")
x
# character(0)
class(x)
# [1] "Date"
x[1] <- "2015-08-12"
x - Sys.Date()
# Time difference of -175 days
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

Please see other answers


the simplest maybe?

vct_dates <- vector()
class(vct_dates)="Date"
HubertL
  • 19,246
  • 3
  • 32
  • 51
  • @Pascal Now I know : And I deleted first one – HubertL Feb 04 '16 at 01:21
  • This is a bad solution for two reasons: 1) `vector()` creates a logical vector by default (compare (`str(vct_dates)` with `str(Sys.Date())`), and 2) you generally shouldn't call `class` directly in order to create an object of that class (you should use a constructor or the `as.` method). – Joshua Ulrich Feb 04 '16 at 03:19