Jørgen K. Kanters
Jørgen K. Kanters

Reputation: 874

How do I create a vector of mode='Date'

I want to use the line below in a function

datehit <- vector(mode="Date",length(vectordiagdate))

but I receive an error

> Error in vector(mode = "Date", length(vectordiagdate)) : 
  vector: cannot make a vector of mode 'Date'.

I shall use the dates later with datediff.

What is wrong, and is there a workaround?

Upvotes: 0

Views: 1286

Answers (2)

Hack-R
Hack-R

Reputation: 23210

There's not a storage mode of Date.

Date is a class:

date.vec <- seq(Sys.Date(), Sys.Date()+10, 1) # date vector example
mydate   <- as.Date("1970-01-01")  # class conversion from character to date

Using your example (loosely):

as.vector(data.frame(x = seq(Sys.Date(),Sys.Date()+10,1)), mode = "list")
            x
1  2016-07-11
2  2016-07-12
3  2016-07-13
4  2016-07-14
5  2016-07-15
6  2016-07-16
7  2016-07-17
8  2016-07-18
9  2016-07-19
10 2016-07-20
11 2016-07-21
datehit <- as.Date(datehit$x)

Valid storage modes are:

  • "logical"
  • "integer"
  • "double"
  • "complex"
  • "raw"
  • "character"
  • "list"
  • "expression"
  • "name"
  • "symbol"
  • "function"

Upvotes: 1

Gavin Simpson
Gavin Simpson

Reputation: 174853

If you want something similar to how one often uses vector(), as a template object to fill in, then you could do

as.Date(rep(NA, length = 10))

> (foo <- as.Date(rep(NA, length = 10)))
 [1] NA NA NA NA NA NA NA NA NA NA
> class(foo)
[1] "Date"

We can't use NULL as the object to rep as that throws a warning to annoy us as as.Date chokes on NULL too.

Upvotes: 1

Related Questions