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

Sequence with varying step size defined by a vector

I need to create a sequence from 1 to let’s say 100 (it doesn’t matter), with alternating step size not following any particular distribution or rule. The exact step size can only be defined by a numerical vector:

vec <- c(1,1,2,1,3,1,1,1,1,4,1)

How do I end up with the following sequence out of the above vector?

seq <- c(1,2,3,5,6,9,10,11,12,13,17,18)

The parameter by = from the seq function does not accept a vector as input, so any ideas or suggestions on how to tackle this are greatly appreciated.

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

>Solution :

Use cumsum:

cumsum(c(1, vec))
#[1]  1  2  3  5  6  9 10 11 12 13 17 18

I asked a similar question a year ago, and one very flexible solution is:

seq2 <- function(from, to, by) {
  
  vals <- c(0, cumsum(rep(by, abs(ceiling((to - from) / sum(by))))))
  if(from > to) return((from - vals)[(from - vals) >= to])
  else (from + vals)[(from + vals) <= to]
}

seq2(from = 1, to = sum(vec), by = vec)
#[1]  1  2  3  5  6  9 10 11 12 13 17
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