我有一个小时值(value)。我想计算自上次不为零以来该值连续多少小时为零。对于电子表格或 for 循环来说,这是一项简单的工作,但我希望有一个活泼的矢量化单线来完成这项任务。
x <- c(1, 0, 1, 0, 0, 0, 1, 1, 0, 0)
df <- data.frame(x, zcount = NA)
df$zcount[1] <- ifelse(df$x[1] == 0, 1, 0)
for(i in 2:nrow(df))
df$zcount[i] <- ifelse(df$x[i] == 0, df$zcount[i - 1] + 1, 0)
期望的输出:
R> df
x zcount
1 1 0
2 0 1
3 1 0
4 0 1
5 0 2
6 0 3
7 1 0
8 1 0
9 0 1
10 0 2
最佳答案
William Dunlap 在 R-help 上的帖子是查找与运行长度相关的所有内容的地方。他的 f7 来自 this post是
f7 <- function(x){ tmp<-cumsum(x);tmp-cummax((!x)*tmp)}
在目前的情况下
f7(!x)
.在性能方面有> x <- sample(0:1, 1000000, TRUE)
> system.time(res7 <- f7(!x))
user system elapsed
0.076 0.000 0.077
> system.time(res0 <- cumul_zeros(x))
user system elapsed
0.345 0.003 0.349
> identical(res7, res0)
[1] TRUE
关于r - 在某些值的连续运行中创建计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5012516/