Re: [R] cumsum on chron objects

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Wed 18 May 2005 - 12:49:02 EST

On 5/17/05, Sebastian Luque <sluque@mun.ca> wrote:
> Hello Gabor,
>
> Thanks for your reply. na.locf would replace the NA's with the most recent
> non-NA, so it wouldn't create a sequence of chron dates/times (via
> as.vector, as in your example). To expand my original example:
>
>
> >> On 5/17/05, Sebastian Luque <sluque@mun.ca> wrote:
>
> [...]
>
> >>> DateTime
> >>> 13/10/03 12:30:35
> >>> NA
> >>> NA
> >>> NA
> >>> 15/10/03 16:30:05
> >>> NA
> >>> NA
> >>> ...
>
> I thought one could replace the NA's by the desired interval, say 1 day,
> so if the above chron object was named nachron, one could do:
>
> nachron[is.na(nachron)] <- 1
>
> and, for simplicity, applying on each "block" separately:
>
> cumsum(nachron)
>
> would give:
>
> DateTime
> 13/10/03 12:30:35
> 14/10/03 12:30:35
> 15/10/03 12:30:35
> 16/10/03 12:30:35
>
> for the first "block", and:
>
> DateTime
> 15/10/03 16:30:05
> 16/10/03 16:30:05
> 17/10/03 16:30:05
> ...
>
> for the second one. Since there are not too many blocks I may end up doing
> it in Excel, but it would be nice to know how to do it in R!

I did not understand that you wanted a sequence.

If x and x.locf are as in the previous response then:

   my.seq <- function(x) seq(from = x[1], len = length(x))    chron(unlist(tapply(x, x.locf, my.seq)))

or if you want to use cumsum:

   xx <- as.vector(x); xx[is.na(xx)] <- 1    chron(unlist(tapply(xx, x.locf, cumsum)))



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed May 18 12:53:23 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:50 EST