Modify complicated character vector automatically

Viewed 51

I have a complicated character vector, whereby each element of the vector consists of numbers and letters. I want to simplify this vector, so that sequences of numbers and/or letters are put into ranges. Here is an example, how the input and output vectors should look like:

# Input vector
input_vec <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11")

# Here some function should be applied, to create the desired output vector automatically

# Desired output vector
output_vec <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11")

I am sure there must be a way to build a function or to use a package, to do this in an automatized way, but unfortunately I am struggling to find a solution. Any help is highly appreciated!

UPDATE: Added an even more complicated vector

input_vec2 <- c("1,2,3,4,5", "1,2,3,5,6,7,8", "2,3,4,5", "A,B,C", "1,2,3,4,5,A,B,8,9,10,11", 
"1", "1,2,3,-4", "lala,3") # This part is new

output_vec2 <- c("1-5", "1-3,5-8", "2-5", "A-C", "1-5,A-B,8-11",
"1", "1-3,-4", "lala,3") # This part is new
1 Answers
Related