r - 在某些值的连续运行中创建计数器

标签 r

我有一个小时值(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/

相关文章:

r - 带有插入符号错误的 SVM 分类(基本)

r - 在 R 中通过 git2r::clone 使用 SSH 身份验证时获取 `unsupported URL protocol`

用R中的列名替换行值

r - 如何编写 Median 函数以用于 Ggplot 图,以适应 R 数据集中的不同项目

从第一个字符到字符串末尾的正则表达式

r - 使用 R 将多个文件从多个文件夹复制到单个文件夹

R eulerr 包 - 显示错误的欧拉图

r - 从多列中仅获取值(非 0、非 NA)

r - 再次 : Setting the environment within a function

动态重命名变量