如何找到数字序列中连续数字的总数

how to find the total number of consecutive digits in a sequence of numbers

我有一个数字列表 [2554, 201, 452, 3111, 4133, 2210, 1235, 430, 4210, 11, 513, 1305, 2550, 5312, 512, 3535, 1014, 4013, 234、4112、13、2433、5233、4500]。我试图找出这些数字中有许多包含连续数字。例如 2554 有连续的数字 (5),但 513 和 3535 没有。我知道连续数字的总数是 24 个中的 10 个。

#my code
count = 0
z = c(2554, 201, 452, 3111, 4133, 2210, 1235, 430, 4210, 11, 513, 1305, 2550, 5312, 512, 3535, 1014, 4013, 234, 4112, 13, 2433, 5233, 4500)
for(i in 1:24){
  if((grep(pattern = "\d{2}", x = z[i])) == 1){
    count = count + 1
  }
}

我正在尝试使用 grep,但它不起作用,我做错了什么吗?

您不需要 forgrep/grepl 中循环,因为它们是矢量化的。

要查找连续的数字,可以使用grepl中捕获组的第一个数字的反向引用。

sum(grepl('(\d)\1', z))
#[1] 10

或与 grep

类似
length(grep('(\d)\1', z))

要知道哪些数字有连续的数字,可以在grep中使用value = TRUE

grep('(\d)\1', z, value = TRUE)
#[1] "2554" "3111" "4133" "2210" "11"   "2550" "4112" "2433" "5233" "4500"

我们可以使用str_detect

library(stringr)
sum(str_detect(z, '(\d)\1'))
#[1] 10

您可以使用 'rle' 找到 'runs' 个字符

library(tidyverse)
z = c(2554, 201, 452, 3111, 4133, 2210, 
      1235, 430, 4210, 11, 513, 1305, 
      2550, 5312, 512, 3535, 1014, 
      4013, 234, 4112, 13, 2433, 5233, 4500)

# split out to separate character each digit and then use 'rle' to
# look for 'runs' of the characters
as_char <- map_dfr(z, ~{
  str <- strsplit(as.character(.x), '')[[1]]
  rle_str <- rle(str)
  # find which have runs > 1
  indx <- which(rle_str$lengths > 1)
  tibble(input = .x, count = rle_str$lengths[indx], value = rle_str$values[indx])
})
as_char

> as_char
# A tibble: 10 x 3
input count value
<dbl> <int> <chr>
  1  2554     2 5    
2  3111     3 1    
3  4133     2 3    
4  2210     2 2    
5    11     2 1    
6  2550     2 5    
7  4112     2 1    
8  2433     2 3    
9  5233     2 3    
10  4500     2 0