[R] cumsum on chron objects

Gabor Grothendieck ggrothendieck at gmail.com
Wed May 18 04:49:02 CEST 2005


On 5/17/05, Sebastian Luque <sluque at 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 at 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)))




More information about the R-help mailing list