【问题标题】:How many of the numbers are consecutive in a string一个字符串中连续的数字有多少
【发布时间】:2022-11-14 05:30:44
【问题描述】:

有这个向量:

vector <- c("236", "234", "", "12", "24", "3")

[1] "236" "234" ""    "12"  "24"  "3"

我想检查每个元素中有多少个连续数字。

预期输出:

2 3 0 2 0 0

我不知道该怎么做!

【问题讨论】:

    标签: r numbers sequence


    【解决方案1】:

    一种可能的解决方案:

    sapply(strsplit(vector,""),
           function(x) {s <- sum(diff(as.numeric(unlist(x)))==1); 
                        if (s) {s+1} else 0})
    
    [1] 2 3 0 2 0 0
    

    【讨论】:

      【解决方案2】:

      我想这可以完成工作:

      vector <- c("236", "234", "", "12", "24", "3")
      
      sapply(strsplit(vector, ""), function(x) {
        r <- rle(diff(as.numeric(x) - seq(length(x))))
        if(0 %in% r$values) max(r$lengths[r$values == 0]) + 1 else 0
      })
      #> [1] 2 3 0 2 0 0
      

      创建于 2022-11-13 reprex v2.0.2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多