[R] subtracting rows for unique

arun smartpink111 at yahoo.com
Wed Jul 24 15:35:08 CEST 2013



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.



________________________________
From: farnoosh sheikhi <farnoosh_81 at yahoo.com>
To: "smartpink111 at yahoo.com" <smartpink111 at yahoo.com> 
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 



More information about the R-help mailing list