[R] calculate time from dates

Thu Jul 11 13:00:07 CEST 2013

```Hello,

The functions in stackoverflow need a date 'format' argument.

# Functions from
#
http://stackoverflow.com/questions/1995933/number-of-months-between-two-dates
# with a 'format' argument added
#
# turn a date into a 'monthnumber' relative to an origin
monnb <- function(d, format = "%Y-%m-%d") {
lt <- as.POSIXlt(as.Date(d, origin="1900-01-01", format = format))
lt\$year*12 + lt\$mon
}
# compute a month difference as a difference between two monnb's
mondf <- function(d1, d2, format = "%Y-%m-%d") {
monnb(d2, format = format) - monnb(d1, format = format)
}

ID date
1 4/12/2008
1 4/13/2008
1 5/11/2008
2 3/21/2009
2 4/22/2009
2 8/05/2009

dat2 <- data.frame(ID = dat1\$ID, month = mondf("01/01/2008", dat1\$date,
format = "%m/%d/%Y") + 1)

# Now keep just the last one if month diffs are equal
result <- with(dat2, aggregate(month, list(ID, month), FUN = tail, 1))[1:2]
names(result) <- names(dat2)
result

Hope this helps,

Em 11-07-2013 11:03, andrija djurovic escreveu:
> Hi.
>
> See
> http://stackoverflow.com/questions/1995933/number-of-months-between-two-dates
>
> Andrija
>
>
> On Thu, Jul 11, 2013 at 11:56 AM, Gallon Li <gallon.li at gmail.com> wrote:
>
>> My data are from 2008 to 2010, with repeated measures for same subjects. I
>> wish to compute number of months since january 2008.
>>
>> The data are like the following:
>>
>> ID date
>> 1 4/12/2008
>> 1 4/13/2008
>> 1 5/11/2008
>> 2 3/21/2009
>> 2 4/22/2009
>> 2 8/05/2009
>> ...
>>
>> the date column are in the format "%m/%d/%y". i wish to obtain
>>
>> ID month
>> 1 4
>> 1 4
>> 1 5
>> 2 15
>> 2 16
>> 2 20
>> ...
>>
>> also, for the same ID with two identical month, I only want to keep the
>> last one. can any expert help with this question?
>>
>>          [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help