Calculate cumsum() while ignoring NA values

后端 未结 4 1566
醉话见心
醉话见心 2020-11-27 20:49

Consider the following named vector x.

( x <- setNames(c(1, 2, 0, NA, 4, NA, NA, 6), letters[1:8]) )
# a  b  c  d  e  f  g  h 
# 1  2  0 NA           


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 21:29

    It's an old question but tidyr gives a new solution. Based on the idea of replacing NA with zero.

    require(tidyr)
    
    cumsum(replace_na(x, 0))
    
     a  b  c  d  e  f  g  h 
     1  3  3  3  7  7  7 13 
    

提交回复
热议问题