Home > Software design >  How many of the numbers are consecutive in a string
How many of the numbers are consecutive in a string

Time:11-14

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!

CodePudding user response:

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

CodePudding user response:

I guess this does the job:

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

Created on 2022-11-13 with reprex v2.0.2

CodePudding user response:

Another option

library(matrixStats)
v1 <- rowSums(rowDiffs(as.matrix(read.fwf(textConnection(paste(vector,
   collapse = "\n")), widths = rep(1, 3)))) == 1, na.rm = TRUE)
replace(v1, v1 != 0, v1[v1!=0]   1)
[1] 2 3 0 2 0 0
  • Related