如何在连续字符串结尾处重置cumsum

时间:2016-04-06 04:32:56

标签: r

如果我有以下载体:

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

如何计算所有连续1的累积总和,每次命中0时重置?

因此,所需的输出将如下所示:

> y
[1] 1 2 3 0 0 0 0 1 2 0 0 1 2 3 0 0 1 2 3 4 0 0 0 0 1 2 3

3 个答案:

答案 0 :(得分:4)

这有效:

 #body {            
       border: 1px double black;
       } 

 #checkout {                    //this is just a head at the top
     text-align:left;
     border-bottom: 1px solid black;
     }
 #contactInput{
    clear:right;
    padding:.5em;

   }

 #invisible{
   float:right;
   padding:.5em;

    }

它非常依赖于你只有1和0的特殊情况,但对于这种情况它很有效!更好的是,@ nicola建议改进:

unlist(lapply(rle(x)$lengths, FUN = function(z) 1:z)) * x
# [1] 1 2 3 0 0 0 0 1 2 0 0 1 2 3 0 0 1 2 3 4 0 0 0 0 1 2 3

答案 1 :(得分:1)

我阅读this post有关如何拆分矢量的信息,并使用@Calimo的splitAt2

所以它是这样的:

splitAt2 <- function(x, pos) {
        out <- list()
        pos2 <- c(1, pos, length(x)+1)
        for (i in seq_along(pos2[-1])) {
                out[[i]] <- x[pos2[i]:(pos2[i+1]-1)]
        }
        return(out)
}

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

where_split = which(x == 0)

x_split = splitAt2(x, where_split)

unlist(sapply(x_split, cumsum))
# [1] 1 2 3 0 0 0 0 1 2 0 0 1 2 3 0 0 1 2 3 4 0 0 0 0 1 2 3

答案 2 :(得分:1)

这是另一个选项

library(data.table)
ave(x, rleid(x), FUN=seq_along)*x
#[1] 1 2 3 0 0 0 0 1 2 0 0 1 2 3 0 0 1 2 3 4 0 0 0 0 1 2 3

或没有任何套餐

ave(x, cumsum(c(TRUE, x[-1]!= x[-length(x)])), FUN=seq_along)*x
#[1] 1 2 3 0 0 0 0 1 2 0 0 1 2 3 0 0 1 2 3 4 0 0 0 0 1 2 3