【问题标题】:Function to count of consecutive digits in a string vector计算字符串向量中连续数字的函数
【发布时间】:2021-12-30 08:38:55
【问题描述】:

我想创建一个函数,它接受一个至少有 1 个元素并包含数字 2 到 5 的字符串对象,并确定是否有至少 N 长度的连续数字,其中 N 是实际数字值。

如果是,则返回字符串 true,否则返回字符串 false。

例如:

Input: "555123" 
Output: false

因为 5 只找到了 3 次而不是 5。

或者:

Input: "57333" 
Output: true

因为 3 恰好被找到了 3 次。

【问题讨论】:

    标签: r function stringr


    【解决方案1】:

    如果您正在使用基础 R,请尝试 rle + strsplit

    f <- function(s) {
      with(
        rle(unlist(strsplit(s, ""))),
        any(as.numeric(values) <= lengths & lengths > 1)
      )
    }
    

    你会看到

    > f("555123")
    [1] FALSE
    
    > f("57333")
    [1] TRUE
    

    【讨论】:

      【解决方案2】:

      聚会迟到了,但也许仍然值得你花时间:

      数据:

      x <- c("555123", "57333", "21112", "12345", "22144", "44440")
      

      用允许的数字定义向量:

      digits <- 2:5
      

      使用多个反向引用定义交替模式:

      patt <- paste0("(", digits, ")\\", c(1, digits), "{", digits - 1, "}", collapse = "|")
      

      patt 输入到str_detect

      library(stringr)
      str_detect(x, patt)
      [1] FALSE  TRUE FALSE FALSE  TRUE  TRUE
      

      【讨论】:

        【解决方案3】:

        您可以检查table 中的值是否对应names

        x <- c('555123', '57333')
        
        f <- \(x) {
          s <- strsplit(x, '')
          lapply(s, \(x) {
            tb <- table(x)
            names(tb) == tb
            }) |> setNames(x)
        }
        
        f(x)
        # $`555123`
        # x
        #    1     2     3     5 
        # TRUE FALSE FALSE FALSE 
        # 
        # $`57333`
        # x
        #    3     5     7 
        # TRUE FALSE FALSE 
        

        【讨论】:

          【解决方案4】:

          运行长度编码函数rle可用于计算字符串中值的连续出现次数,使用any函数查看是否满足任何查询长度。

          f <- function(s){
            ff = Vectorize(\(x, i) any(x$lengths[x$values == i] >= i), "i")
            s = rle(strsplit(s, "")[[1]])
            any(ff(s, 2:5))
          }
          
          f("555123")
          [1] FALSE
          f("57333")
          [1] TRUE
          

          【讨论】:

            【解决方案5】:

            另一种方法是:

            my_func <- function(x) {
              
              as.numeric(unlist(strsplit(x, ""))) -> all
              table(all[all %in% 2:5]) -> f 
              any(names(f) == f)
              
            }
            
            # Input <- "555123"
            # (my_func(Input))
            # FALSE
            
            # Input <- "57333" 
            # (my_func(Input))
            # TRUE
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-04-23
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-01-24
              相关资源
              最近更新 更多