Cumulative sum for positive numbers only

前端 未结 9 1191
梦谈多话
梦谈多话 2020-12-09 08:13

I have this vector :

x = c(1,1,1,1,1,0,1,0,0,0,1,1)

And I want to do a cumulative sum for the positive numbers only. I should have the fol

相关标签:
9条回答
  • 2020-12-09 08:50
    x=c(1,1,1,1,1,0,1,0,0,0,1,1)
    cumsum_ <- function(x) {
      r <- rle(x)
      s <- split(x, rep(seq_along(r$values), rle(x)$lengths))
      return(unlist(sapply(s, cumsum), use.names = F))
    }
    (xc <- cumsum_(x))
    # [1] 1 2 3 4 5 0 1 0 0 0 1 2
    
    0 讨论(0)
  • 2020-12-09 08:50
    x<-c(1,1,1,1,1,0,1,0,0,0,1,1)
    
    skumulowana<-function(x) {
      dl<-length(x)
      xx<-numeric(dl+1)
      for (i in 1:dl){
        ifelse (x[i]==0,xx[i+1]<-0,xx[i+1]<-xx[i]+x[i])
      }
    wynik<<-xx[1:dl+1]
    return (wynik)
    }
    
    skumulowana(x)
    ## [1] 1 2 3 4 5 0 1 0 0 0 1 2
    
    0 讨论(0)
  • 2020-12-09 08:52

    I dont know much of R but i have written a small code in Python. Logic remains the same in all language. Hope this will help you

    x=[1,1,1,1,1,0,1,0,0,0,1,1]
    tot=0
    for i in range(0,len(x)):
        if x[i]!=0:
            tot=tot+x[i]
            x[i]=tot
        else:
            tot=0
    print x
    
    0 讨论(0)
提交回复
热议问题