【问题标题】:Determine repeating numbers in a string in R确定R中字符串中的重复数字
【发布时间】:2021-02-11 21:53:58
【问题描述】:

我正在尝试识别具有重复数字序列的数据框中的列值。 比如

> df
   ColA
1 66046
2 73947
3 67456
4 67217
5 66861
6 67658

我想返回 66046, 66861 因为 6 连续出现。 我已经尝试了以下...

df %>% filter(str_detect(as.String(df[1]), "[66]"))  #with and without the squared brackets.
df[unlist(gregexpr("[6]{2}[[:digit:]]", df[1])), ][1]

很明显,这是行不通的。任何帮助表示赞赏。

谢谢

【问题讨论】:

    标签: r regex string detect


    【解决方案1】:

    我们可以指定计数

    library(dplyr)
    library(stringr)
    df %>%
       filter(str_detect(ColA, "6{2,}"))
    

    -输出

    #   ColA
    #1 66046
    #5 66861
    

    数据

    df <- structure(list(ColA = c(66046L, 73947L, 67456L, 67217L, 66861L, 
    67658L)), class = "data.frame", row.names = c("1", "2", "3", 
    "4", "5", "6"))
    

    【讨论】:

    • 非常感谢..这有效..有没有办法可以检索任何数字连续重复的值..不仅仅是6..我试过 [[:digits:]] 6 的地方,但返回一切。
    • ColA 1 66006 2 67003 3 67226 4 73933
    【解决方案2】:

    使用

    library(dplyr)
    library(stringr)
    df %>%
       filter(str_detect(ColA, "(\\d)\\1"))
    

    见proof

    NODE EXPLANATION
    ( group and capture to \1:
    \d digits (0-9)
    ) end of \1
    \1 what was matched by capture \1

    【讨论】:

      【解决方案3】:

      聚会迟到了,但这是base R 中的解决方案:

      df[which(grepl("(\\d)\\1", df$ColA)),]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 2017-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多