Re: [R] Manipulating dates

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Wed 15 Jun 2005 - 08:00:52 EST

On 6/14/05, Richard Hillary <r.hillary@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.



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Jun 15 08:03:57 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:38 EST