Advertisements
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.
>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