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)
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With