R:如何让 str_count 查找两个特定数字之间出现零的次数?

R: how can i make str_count look for the number of occurences of zero between two specific numbers?

我有一个数据框,其中有一列表示事件的开始 (1) 和结束 (2)。事件的持续时间是 1 到 2 之间的零的个数。此事件可能会发生多次。该列如下所示:

event <- c(1002, 100000000000000000, 10002000102000, 10000, 100000210200000000, 10020000010200000)

我试过 stringr::str_count(string = event, pattern = "0"),当然,这给了我零的总数。我需要的是第一个 1 和 2 之间的零的数量。应该删除 2 之后的零。

2 
17
3 1
4
5 1
2 1

我不知道该怎么做,可能是我这里的方法全错了。谁能给我一些指导?

基础 R 选项 -

#To avoid scientific notation in numbers
options(scipen = 99)
sapply(strsplit(as.character(event), ''), function(x) {
  #position of 1
  one <- which(x == 1)
  #position of 2
  two <- which(x == 2)
  #If event is still going on
  if(length(two) == 0) {
    #Calculate last position - position 1
    two <- length(x)
    return(two - one)
  }
  return(two - one - 1)
})

#[[1]]
#[1] 2

#[[2]]
#[1] 17

#[[3]]
#[1] 3 1

#[[4]]
#[1] 4

#[[5]]
#[1] 5 1

#[[6]]
#[1] 2 1

一种tidyverse方法(预先将数字转换为字符;使用函数format是为了避免数字的科学格式):

library(tidyverse)

event <- format(c(1002, 100000000000000000, 10002000102000, 10000, 100000210200000000, 10020000010200000), scientific = F)

event %>% 
  str_extract_all("(?<=1)0+") %>% 
  map(~ nchar(.x))
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 17
#> 
#> [[3]]
#> [1] 3 1
#> 
#> [[4]]
#> [1] 4
#> 
#> [[5]]
#> [1] 5 1
#> 
#> [[6]]
#> [1] 2 1