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 <iaingallag...@btopenworld.com> wrote: > >> From: Iain Gallagher <iaingallag...@btopenworld.com> >> Subject: [R] median time period >> To: r-help@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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.