[R] Manipulating dates

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 15 00:00:52 CEST 2005


On 6/14/05, Richard Hillary <r.hillary at imperial.ac.uk> wrote:
> Hello,
>          Given a vector of characters, or factors, denoting the date in
> the following way: 28/03/2000, is there a method of
> 1) Computing the earliest of these dates;
> 2) Using this as a base, then converting all the other dates into merely
> the number of days after this minimum date


Convert dates to chron (whose default date format is the
one needed here); convert that to numeric (which will be the 
number of days since some origin) and then do the indicated 
subtraction:

	library(chron)
	x <- as.character(x)  # can omit if already character
	x.num <- as.numeric(chron(x))
	x - x.num - min(x.num)

Alternately convert it to Date and use julian (or convert
x.Date to numeric and use subtraction, as with chron):

	x <- as.character(x) # can omit in latest R 2.1.0 patched
	x.Date <- as.Date(x, "%m/%d/%Y")
	julian(x.Date, min(x.Date))

The as.Date.factor method in the latest R 2.1.0 patched
supports the format string (second argument of as.Date) for
factors but older versions of R did not. If your x is a 
factor but you do not want to upgrade right now start off
with the statement: x <- as.character(x)

More info on dates is in R News 4/1.




More information about the R-help mailing list