[R] Calculating number of elapsed days from starting date

Berend Hasselman bhh at xs4all.nl
Thu Sep 27 11:05:23 CEST 2012


On 27-09-2012, at 07:16, Marcel Curlin <cemarcel at u.washington.edu> wrote:

> Hi 
> I have data for events in rows, with columns for person and date. Each
> person may have more than one event;
> 
> tC <- textConnection("
> Person	date
> bob	1/1/00
> bob	1/2/00
> bob	1/3/00
> dave	1/7/00
> dave	1/8/00
> dave	1/10/00
> kevin	1/2/00
> kevin	1/3/00
> kevin	1/4/00
> ")
> data <- read.table(header=TRUE, tC)
> close.connection(tC)
> rm(tC)
> 
> I would like to add a new column to my dataframe containing the calculated
> number of elapsed days from the starting date for each person. So the new
> dataframe would read
> 
> Person	date	Days
> bob	1/1/00	0
> bob	1/2/00	1
> bob	1/3/00	2
> dave	1/7/00	0
> dave	1/8/00	1
> dave	1/10/00	3
> kevin	1/2/00	0
> kevin	1/3/00	1
> kevin	1/4/00	2
> 
> Not sure how to do this, tried looking through the forum but didn't find
> anything that seemed to apply. Suggestions appreciated.


You could do this

DF$realdate <- as.Date(as.character(DF$date),format="%m/%d/%y")
DF$Days <- ave(as.numeric(DF$realdate), by=DF$Person, FUN=function(x) x-x[1])

If you don't want the as.character then you should add stringsAsFactors=FALSE to the read.table argument list.

Berend




More information about the R-help mailing list