计算特定值的行数(并反向计数)

Count number of rows to a specific value (and count in reverse)

我有这个数据

data.frame(x1 = c(rep(0, 3), rep(1, 4), rep(0, 4)))

我想这样数:

X2 列

谁能解释一下我该怎么做?谢谢!

这是 rle 的一个选项:

df <- data.frame(x1 = c(rep(0, 3), rep(1, 4), rep(0, 4)))

df$x2 <- unlist(with(rle(df$x1), mapply(function(x, y) 
                if(x == 0) rev(-seq(y)) else seq(y) - 1, values, lengths)))
df

#   x1 x2
#1   0 -3
#2   0 -2
#3   0 -1
#4   1  0
#5   1  1
#6   1  2
#7   1  3
#8   0 -4
#9   0 -3
#10  0 -2
#11  0 -1

这也可以借助ave写成:

df$x2 <- ave(df$x1, data.table::rleid(df$x1), FUN = function(x) 
              if(x[1] == 0) rev(-seq_along(x)) else seq_along(x) - 1)

两个代码的逻辑是一样的。我们创建连续的 0 和 1 值组,如果组值为 0,则创建从 1 到组长度的序列,使其为负并反转值。如果组值为 1,则创建一个从 0 到组长度 - 1 的序列。

我们可以使用 data.table

中的 rleid
library(data.table)
setDT(df1)[, x2 := (seq_len(.N)-1) - c(0, .N)[(1 + all(!x1))], rleid(x1)]

-输出

df1
#    x1 x2
# 1:  0 -3
# 2:  0 -2
# 3:  0 -1
# 4:  1  0
# 5:  1  1
# 6:  1  2
# 7:  1  3
# 8:  0 -4
# 9:  0 -3
#10:  0 -2
#11:  0 -1