Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cumulative sum while a condition is met with NA

Imagine I have these two vectors:

a <- c(0,0,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3)
b <- c(NA,NA,NA,3,NA,NA,5,NA,NA,4,5,NA,2,NA,1,NA,NA,1)

And I am trying to have the cumulative sum by group that would end up in something like this:

c(NA,NA,NA,3,NA,NA,8,NA,NA,4,9,NA,11,NA,1,NA,NA,2)

I am trying with do.call(rbind,by(b,a,cumsum)) but it does not work, it returns an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Warning message:
In (function (..., deparse.level = 1)  :
  number of columns of result is not a multiple of vector length (arg 1)

Any ideas?
Thanks!

>Solution :

You could use ave.

ave(b, a, FUN=\(x) {r <- cumsum(replace(x, is.na(x), 0)); replace(r, is.na(x), NA)})
# [1] NA NA NA  3 NA NA  8 NA NA  4  9 NA 11 NA  1 NA NA  2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading