【问题标题】:Count largest number of consecutive zeros in a vector using a vectorized function使用向量化函数计算向量中连续零的最大数量
【发布时间】:2021-02-21 14:16:24
【问题描述】:

我想构建一个以向量作为参数并返回最大数量的连续零的函数。例如:

a <- c(0,0,1,1,0)
b <- c(0,1,3,10,0,0,0)
x <- count_max_consecutive_zeros(a)
y <- count_max_consecutive_zeros(b)

应该导致 x=2 和 y=3。我可以选择明显的解决方案并循环:

count_max_consecutive_zeros <- function(x) {
  max_count <- 0
  current_count <- 0
  for (i in 1:length(x) {
   if(x[i] == 0) {
     current_count = current_count + 1
  } else {
    if(current_count > max_count) {
      max_count <- current_count
    }
    current_count <- 0
  }
}

此解决方案适用于短向量,但是我必须在数万条目长的向量上使用此函数数千次,所以我担心会遇到性能问题。有没有等价于count_max_consecutive_zeros的向量化函数?

【问题讨论】:

    标签: r vectorization


    【解决方案1】:

    rleid 的选项

    library(data.table)
    max(tapply(a[a==0], rleid(a)[a == 0], FUN = length))
    #[1] 2
    

    【讨论】:

    • 绝对是一个不错的选择,但我不想再添加一个依赖项。我想我会坚持@GKi 的解决方案
    【解决方案2】:

    您可以使用rlemax计算连续零的最大数量

    x <- rle(a==0)
    max(x$lengths[x$values == TRUE])
    #[1] 2
    

    【讨论】:

    • 非常感谢您,先生!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多