TarJae
TarJae

Reputation: 79174

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!

Upvotes: 3

Views: 64

Answers (3)

akrun
akrun

Reputation: 887571

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

Upvotes: 1

Waldi
Waldi

Reputation: 41240

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

Upvotes: 6

Allan Cameron
Allan Cameron

Reputation: 174338

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

Upvotes: 4

Related Questions