[R] puzzled by math on date-time objects

Stavros Macrakis macrakis at alum.mit.edu
Tue Mar 10 22:57:19 CET 2009


It does seem sensible that median and quantile would work for the
POSIXct, Date, and other classes for which they are logically
well-defined, but strangely enough, they do not (except for odd-length
input).  The summary function has a special case (summary.POSIXct)
which does the straightforward, obvious thing here.  I do not
understand why this is not done by median and quantile themselves.

Conversely, for the complex class, median and quantile do not give an
error but instead produce meaningless results (since the complexes do
not form an ordered field).

There are other operations as well that don't do the natural, useful
thing on a variety of classes, including POSIXct, Date, and difftime:

> dates <- c(as.Date('2000-01-01'), as.Date('2000-01-05'), as.Date('1990-08-09'), as.Date('2008-02-29'))
> median(dates)
Error in Summary.Date(c(10957, 10961), na.rm = FALSE) :
  sum not defined for Date objects
> quantile(dates,.5)
Error in Ops.Date((1 - h), qs[i]) : * not defined for Date objects
> gaps <- diff(sort(dates))
> gaps
Time differences in days
[1] 3432    4 2977
> cumsum(gaps)
Error in Math.difftime(gaps) :
  'cumsum' not defined for "difftime" objects
> rle(dates)
Error in rle(dates) : 'x' must be an atomic vector
> rle(gaps)
Error in rle(gaps) : 'x' must be an atomic vector

I have documented some of these issues in my email "Semantics of
sequences in R" (22/02/2009 3:42 PM) and other emails, and I have
proposed to write code to resolve them, but have not received a warm
reception.

All I can suggest at this point is that you write your own versions of
these functions. Or perhaps one of us will write a CRAN package,
though this really seems like core behavior.

            -s

On Tue, Mar 10, 2009 at 11:44 AM, Denis Chabot <chabotd at globetrotter.net> wrote:
> I don't understand the following. When I create a small artificial set of
> date information in class POSIXct, I can calculate the mean and the median:
> ...But for real data (for this post, a short subset is in object c)  that I
> have converted into a POSIXct object, I cannot calculate the median with
> median(), though I do get it with summary():




More information about the R-help mailing list