Search code examples
rnumberssequence

How many of the numbers are consecutive in a string


Having this vector:

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

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

I would like to check how many consecutive numbers there are in each element.

Expected output:

2 3 0 2 0 0

I have no idea how to do this!


Solution

  • One possible solution:

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