Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading