Thank you so much.
It worked perfectly:)
 


________________________________


Cc: R help <r-help@r-project.org> 
Sent: Tuesday, July 23, 2013 1:34 PM
Subject: Re: subtracting rows for unique 




Hi,
Try:
dat1<- read.table(text="
ID Date x2 x1          x3 
56 25-Jun-01 10 2  126 
56 29-Oct-01 10 2  140 
56 18-Mar-02 10 2  445 
56 6-Jun-03 10 2    224 
56 16-Jan-04  10 2    NA 
58 10-Jan-02 10.8 1 715 
58 26-Dec-03 10.8 1    NA 
",sep="",header=TRUE,stringsAsFactors=FALSE) 
 unlist(with(dat1,by(as.Date(Date,format="%d-%b-%y"),ID,FUN=function(x) c(diff(x),NA))),use.names=FALSE)
#[1] 126 140 445 224  NA 715  NA
#or
unlist(lapply(split(dat1,dat1$ID),function(x) c(diff(as.Date(x$Date,format="%d-%b-%y")),NA)),use.names=FALSE)
#[1] 126 140 445 224  NA 715  NA
A.K.



________________________________


Sent: Tuesday, July 23, 2013 3:11 PM
Subject: subtracting rows for unique 



Hi there,

Hope you are doing well.
I have a data set which looks like below, I want to create a new variable (x3-here) which subtracts the date for unique ID.
For example for ID 56, the first value is the difference between  29-Oct, and 25-June.
Thanks for your help and time.




ID Date x2 x1          x3 
56 25-Jun-01 10 2 126 
56 29-Oct-01 10 2 140 
56 18-Mar-02 10 2 445 
56 6-Jun-03 10 2 224 
56 16-Jan-04  NA             NA 
58 10-Jan-02 10.8 1 715 
58 26-Dec-03 10.8 1             NA 

Best,Farnoosh Sheikhi 
	[[alternative HTML version deleted]]

