Reputation: 36607
For example, I tried the following to create a vector of Dates, length 5. None work:
date(5)
Date(5)
vector(5, mode = "Date" )
This works, but wondering if there is a shortcut?
as.Date( numeric( 5 ) )
Also, I see that mode( as.Date("2011-01-01" ) ) is numeric and I understand that the underlying data structure for dates is numeric, but given that vector() only has a mode and length argument, it seems to me that its impossible to create a vector of Date without coercion?
Edit
This is also a solution, except for length = 0?
Date = function( length = 0 )
{
newDate = numeric( length )
class(newDate) = "Date"
return(newDate)
}
Upvotes: 16
Views: 36410
Reputation: 3532
To initialise with missing dates instead of a bunch of 1970-01-01s:
(x = structure(rep(NA_real_, 10 ), class="Date"))
# [1] NA NA NA NA NA NA NA NA NA NA
class(x)
# [1] "Date"
Upvotes: 7
Reputation: 368579
You can use a sequence, or just just add:
R> seq( as.Date("2011-07-01"), by=1, len=3)
[1] "2011-07-01" "2011-07-02" "2011-07-03"
R> as.Date("2011-07-01") + 0:2
[1] "2011-07-01" "2011-07-02" "2011-07-03"
R>
and that both work the same way is a nice illustration of why object-orientation is nice for programming with data.
Date, as you saw, has an underlying numeric representation (of integers representing the number of days since the beginning of Unix time, aka Jan 1, 1970) but it also has a class attribute which makes the formatting, arithmetic, ... behave the way it does utilising the dispatch mechanism in R.
Edit: By the same token, you can also start with a standard vector and turn it into a Date
object:
R> x <- 1:3
R> class(x) <- "Date"
R> x
[1] "1970-01-02" "1970-01-03" "1970-01-04"
R>
Upvotes: 18