Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - how do I declare a vector of Date?

Tags:

r

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)
}
like image 622
SFun28 Avatar asked Jul 21 '11 13:07

SFun28


1 Answers

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> 
like image 163
Dirk Eddelbuettel Avatar answered Oct 16 '22 02:10

Dirk Eddelbuettel