[R] partial cumsum
Carl Witthoft
carl at witthoft.com
Wed Nov 11 23:45:32 CET 2009
quote:
> x <- c(1, 2, 3, NA, 5, 6, 7, 8, 9, 10)
> rev(cumsum(rev(is.na(x))))
[1] 1 1 1 1 0 0 0 0 0 0
A more natural way to do this is
> cumsum(is.na(c(NA,x[-length(x)])))
[1] 1 1 1 1 2 2 2 2 2 2
endquote
Both of which suggest the original problem could also be dealt with by
using rle(). Something like
xna<-is.na(x)
rle(xna)
and then apply cumsum to sections of x based onthe lengths returned by rle
Carl
More information about the R-help
mailing list