Skip to content
Prev 201103 / 398513 Next

how to ignore NA when using cumsum WHILE retaining NAs?

It would really help if you supplied the expected
output for your example.  Does the following do
what you want?
   f <- function(mat) {
      # use t() if you want output to be organized in rows like input
      retval <- t(apply(replace(mat,is.na(mat),0), 1, cumsum))
      replace(retval, is.na(mat), NA)
   }
A slightly different approach that does the same thing is
   g <- function(mat) {
      for(i in seq_len(nrow(mat))) {
         isNotNA <- !is.na(mat[i,])
         mat[i,isNotNA] <- cumsum(mat[i,isNotNA])
      }
      mat
   }
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com