Search code examples
rstrsplit

Transform character with ranges or values into vector of only values in R


I have a character vector c("1:3","4") and what I need is c(1,2,3,4).

What I did so far was to get each element of the original vector, use strsplit on "1:3", retrieve the numbers 1 and 3, form the vector c(1,2,3) and then get the desired vector by concatenating with 4.

Is there any simpler way of doing that?

Thanks in advance.


Solution

  • One option is eval(parse

    unlist(lapply(v1, function(x) eval(parse(text=x))))
    

    Or after the strsplit, get the sequence with :

    unlist(lapply(strsplit(v1, ":"), function(x) Reduce(`:`, as.numeric(x))))
    #[1] 1 2 3 4
    

    data

    v1 <- c("1:3","4")