[R] Calculate days with R
arun
smartpink111 at yahoo.com
Sat Jun 15 20:03:16 CEST 2013
Hi,
May be this helps:
dat1<- read.table(text="
pbnr dat dep dys sop ago mis age female
1 10023 1994-02-21 0.75 1.00 0.50 0.50 0.75 35 1
2 10023 1994-05-25 0.75 1.00 0.50 0.50 0.75 35 1
3 10028 1994-02-01 2.00 1.75 3.00 0.50 1.50 42 1
4 10028 1999-01-15 1.25 0.75 2.25 0.50 0.25 42 1
5 10053 1994-03-16 2.50 0.75 1.25 0.50 1.25 22 1
6 10053 1994-09-23 3.25 1.25 1.25 0.75 2.25 22 1
",sep="",header=TRUE,stringsAsFactors=FALSE)
dat1$dat<- as.Date(dat1$dat)
with(dat1,tapply(dat,list(pbnr),FUN=diff))
#10023 10028 10053
# 93 1809 191
library(plyr)
ddply(dat1,.(pbnr),mutate,Datediff=diff(dat))
# pbnr dat dep dys sop ago mis age female Datediff
#1 10023 1994-02-21 0.75 1.00 0.50 0.50 0.75 35 1 93
#2 10023 1994-05-25 0.75 1.00 0.50 0.50 0.75 35 1 93
#3 10028 1994-02-01 2.00 1.75 3.00 0.50 1.50 42 1 1809
#4 10028 1999-01-15 1.25 0.75 2.25 0.50 0.25 42 1 1809
#5 10053 1994-03-16 2.50 0.75 1.25 0.50 1.25 22 1 191
#6 10053 1994-09-23 3.25 1.25 1.25 0.75 2.25 22 1 191
#or
dat2<-aggregate(dat~pbnr,data=dat1,diff)
colnames(dat2)[2]<- "Datediff"
join(dat1,dat2,by="pbnr")
# pbnr dat dep dys sop ago mis age female Datediff
#1 10023 1994-02-21 0.75 1.00 0.50 0.50 0.75 35 1 93
#2 10023 1994-05-25 0.75 1.00 0.50 0.50 0.75 35 1 93
#3 10028 1994-02-01 2.00 1.75 3.00 0.50 1.50 42 1 1809
#4 10028 1999-01-15 1.25 0.75 2.25 0.50 0.25 42 1 1809
#5 10053 1994-03-16 2.50 0.75 1.25 0.50 1.25 22 1 191
#6 10053 1994-09-23 3.25 1.25 1.25 0.75 2.25 22 1 191
A.K.
Hi, I am new to this forum, and have a problem. I have data that looks like this:
pbnr dat dep dys sop ago mis age female
1 10023 1994-02-21 0.75 1.00 0.50 0.50 0.75 35 1
2 10023 1994-05-25 0.75 1.00 0.50 0.50 0.75 35 1
3 10028 1994-02-01 2.00 1.75 3.00 0.50 1.50 42 1
4 10028 1999-01-15 1.25 0.75 2.25 0.50 0.25 42 1
5 10053 1994-03-16 2.50 0.75 1.25 0.50 1.25 22 1
6 10053 1994-09-23 3.25 1.25 1.25 0.75 2.25 22 1
.....
And I want to know how many days each person (pbnr) has been in
therapy. row 1 is first a date for person 10023 and row 2 the second but
what do I do now????
Thanks for you help!!
Sophie
More information about the R-help
mailing list