cumsum that replaces NA with zero

Hi there,

I am trying to calculate a cumsum in a column that has NA values. I tried this code:

library(dplyr)
library(tidyr)

df3 %>%
  mutate(
    cum_completed = cumsum((replace_na(x, 0))completed), 
    cum_incomplete = cumsum((replace_na(x, 0))incomplete)) %>%
  print()

but get the following error message:

library(tidyr)
df3 %>%

  • mutate(
  • cum_completed = cumsum((replace_na(x, 0))completed), 
    

Error: unexpected symbol in:
" mutate(
cum_completed = cumsum((replace_na(x, 0))completed"

Not sure what is wrong. Any help or advice is much appreciated.

Kind Regards

Aaron

I do not understand what you mean to do with the complete d and incomplete words in our code. Here is an example of computing the cumsum of column B in a toy data frame with and without suing the replace_na function.

df3 <- data.frame(A=1:4,B=c(1,2,NA,4))
df3 %>%
   mutate(
     cum_replace_na = cumsum(replace_na(B, 0)), 
     cum_with_NA = cumsum(B)) %>%
   print()
  A  B cum_replace_na cum_with_NA
1 1  1              1           1
2 2  2              3           3
3 3 NA              3          NA
4 4  4              7          NA

Thank you @FJCC - that worked! And apologies for not explaining the names of the columns. I am creating a cumulative tally of survey responses that have been 'completed' and a cumulative tally of survey responses that are 'incomplete'.

Thank you again!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.