[R] median time period

Marc Schwartz marc_schwartz at me.com
Wed Jun 29 20:18:25 CEST 2011


Iain,

Just to throw out another option, using base R functions:

test <- c('08-04-22', '08-07-28', '09-03-02', '09-03-03', '09-01-30', 
          '09-03-09', '10-02-24', '10-03-05')

> median(as.numeric(diff(as.Date(test, format = "%y-%m-%d"), lag = 4) / 30.44))
[1] 10.54534


This uses the ?diff function which has a Date method (defaulting to units in days) and also a 'lag' option:

> diff(as.Date(test, format = "%y-%m-%d"), lag = 4)
Time differences in days
[1] 283 224 359 367


I use 30.44 above to convert days to months.

HTH,

Marc Schwartz


On Jun 29, 2011, at 10:50 AM, Iain Gallagher wrote:

> Typical - you post to the list and then work it out for yourself!
> 
> Anyway here's my solution
> 
> Toy code as before then:
> 
> intervalsMonths <- 12 * intervals$year + intervals$month
> 
> #convert whole years to months then add the remaining months for that entry in intervals
> 
> medianMonths <- median(as.numeric(intervalsMonths))
> 
> Best
> 
> iain
> 
> --- On Wed, 29/6/11, Iain Gallagher <iaingallagher at btopenworld.com> wrote:
> 
>> From: Iain Gallagher <iaingallagher at btopenworld.com>
>> Subject: [R] median time period
>> To: r-help at r-project.org
>> Date: Wednesday, 29 June, 2011, 16:24
>> Hello List
>> 
>> I'm trying to calculate the median period (in months) of a
>> set of time intervals (between two interventions). 
>> 
>> I have been playing with the lubridate package to create
>> the intervals but I can't think of the right approach to get
>> the median timeperiod.
>> 
>> Toy code:
>> 
>> library(lubridate)
>> test <- c('08-04-22', '08-07-28', '09-03-02',
>> '09-03-03', '09-01-30', '09-03-09', '10-02-24', '10-03-05')
>> test <- ymd(test)
>> intervals <- as.period(test[5:8] - test[1:4])
>> 
>> intervals
>> [1] 9 months and 8 days    7 months and 9
>> days    11 months and 22 days 
>> [4] 1 year and 2 days 
>> 
>> How can I convert this 'period' object to months? From
>> there I think I should just convert to 'numeric' and
>> calculate the median.
>> 
>> Garrett if you're out there - great package but could you
>> help please!?
>> 
>> Best
>> 
>> iain



More information about the R-help mailing list