【问题标题】:Cumulative count of blocks of 1 with 0 separators in a binary vector in RR中二进制向量中具有0个分隔符的1块的累积计数
【发布时间】:2016-05-15 14:48:19
【问题描述】:

我有一个带有二进制向量的数据框,我想对其进行累积计数。但是,我想计算“1 的组”而不是每个单独的 1,并创建一个该计数的新向量,同时保留 0 分隔值。 即

df1 <- data.frame(c(0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1)

n   bin
1    0
2    1
3    1
4    1
5    1
6    0
7    0
8    0
9    1
10   1
11   1
12   1
13   1
14   0
15   0
16   0
17   1
18   1
19   1 

变成

n   bin cumul
1    0     0
2    1     1
3    1     1
4    1     1
5    1     1
6    0     0
7    0     0
8    0     0
9    1     2
10   1     2
11   1     2
12   1     2
13   1     2
14   0     0
15   0     0
16   0     0
17   1     3
18   1     3
19   1     3

我该怎么办?

【问题讨论】:

    标签: r dataframe cumulative-frequency


    【解决方案1】:

    您可以使用包data.table中的rleid函数:

    df1 <- data.frame(bin = c(0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1))
    library(data.table)
    setDT(df1)
    df1[, cumul := rleid(bin)]
    df1[bin == 0, cumul := 0]                  
    df1[bin == 1, cumul := rleid(cumul)]  
    #    bin cumul
    # 1:   0     0
    # 2:   1     1
    # 3:   1     1
    # 4:   1     1
    # 5:   1     1
    # 6:   0     0
    # 7:   0     0
    # 8:   0     0
    # 9:   1     2
    #10:   1     2
    #11:   1     2
    #12:   1     2
    #13:   1     2
    #14:   0     0
    #15:   0     0
    #16:   0     0
    #17:   1     3
    #18:   1     3
    #19:   1     3
    

    【讨论】:

    • 这正是我想要的。非常感谢,@Roland。
    【解决方案2】:

    虽然是手动的:

    l <- rle(df1$c1)$lengths
    v <- rle(df1$c1)$values
    v2 <-  cumsum(v)
    v2[duplicated(v2)] <- 0
    
    df1$cumul <- rep(v2, times = l)
    df1
       c1 cumul
    1   0     0
    2   1     1
    3   1     1
    4   1     1
    5   1     1
    6   0     0
    7   0     0
    8   0     0
    9   1     2
    10  1     2
    11  1     2
    12  1     2
    13  1     2
    14  0     0
    15  0     0
    16  0     0
    17  1     3
    18  1     3
    19  1     3
    

    【讨论】:

      【解决方案3】:

      又一个

      x<-c(0,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1)
      d<-cumsum(diff(c(0,x))>0)
      d[x==0]<-0
      cbind(x,d)
      
      xd [1,] 0 0 [2,] 1 1 [3,] 1 1 [4,] 1 1 [5,] 1 1 [6,] 0 0 [7,] 0 0 [8,] 0 0 [9,] 1 2 [10,] 1 2 [11,] 1 2 [12,] 1 2 [13,] 1 2 [14,] 0 0 [15,] 0 0 [16,] 0 0 [17,] 1 3 [18,] 1 3 [19,] 1 3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-09
        • 2018-02-27
        • 2021-08-30
        • 2013-06-19
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2013-03-22
        相关资源
        最近更新 更多