Search code examples
rvectorsequenceindices

R: Select multiple values from vector of sequences


In R I'm trying to figure out how to select multiple values from a predefined vector of sequences (e.g. indices = c(1:3, 4:6, 10:12, ...)). In other words, if I want a new vector with the 3rd, 5th, and 7th entries in "indices", what syntax should I use to get back a vector with just those sequences intact, e.g. c(10:12, ...)?


Solution

  • If I understand correctly, you want the 3rd, 5th, and 7th entry in c(1:3, 4:6, 10:12, ...), which means you want extract specific sets of indices from a vector.

    When you do something like c(1:3, 4:6, ...), the resulting vector isn't what it sounds like you want. Instead, use list(1:3, 4:6, ...). Then you can do this:

    indices <- list(1:3, 4:6, 10:12, 14:16, 18:20)
    
    x <- rnorm(100)
    
    x[c(indices[[3]], indices[[5]])]
    

    This is equivalent to:

    x[c(10:12, 18:20)]
    

    That is in turn equivalent to:

    x[c(10, 11, 12, 18, 19, 20)]
    

    Please let me know if I've misinterpreted your question.