3

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!

TarJae
  • 72,363
  • 6
  • 19
  • 66

3 Answers3

6

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
Waldi
  • 39,242
  • 6
  • 30
  • 78
4

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

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
akrun
  • 874,273
  • 37
  • 540
  • 662