Search code examples
rvectorintegersequence

Using a vector of integers in the `from` argument of seq


Is there any function that can generate a vector of numbers using multiple values in seq(from = )?

For example, I would like to generate a vector of numbers from 1:3 to 50 with an increment of 7. The output should be

sort(c(seq(1, 50, 7), seq(2, 50, 7), seq(3, 50, 7)))
[1]  1  2  3  8  9 10 15 16 17 22 23 24 29 30 31 36 37 38 43 44 45 50

Currently I'm using a sapply to wrap around 1:3, which I think is not very elegant.

sort(unlist(sapply(1:3, \(x) seq(x, 50, 7))))

Solution

  • This is a vectorised version using sequence().

    No loops required. :)

    seqv <- function(from, to, by = 1){
      sequence( ((to - from) / by) + 1, from = from, by = by)
    }
    
    sort(seqv(1:3, 50, 7))
    [1]  1  2  3  8  9 10 15 16 17 22 23 24 29 30 31 36 37 38 43 44 45 50