R - Generate a sequence of numbers
I find the sequence
function to be helpful in this case. If you had your data in a structure like this:
(info <- data.frame(start=c(1, 144, 288), len=c(6, 6, 6)))
# start len
# 1 1 6
# 2 144 6
# 3 288 6
then you could do this in one line with:
sequence(info$len) + rep(info$start-1, info$len)
# [1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
Note that this solution works even if the sequences you're combining are different lengths.
Here's one approach:
unlist(lapply(c(0L,(1:2)*144L-1L),`+`,seq_len(6)))
# or...
unlist(lapply(c(1L,(1:2)*144L),function(x)seq(x,x+5)))
Here's a way I like a little better:
rep(c(0L,(1:2)*144L-1L),each=6) + seq_len(6)
Generalizing...
rlen <- 6L
rgap <- 144L
rnum <- 3L
starters <- c(0L,seq_len(rnum-1L)*rgap-1L)
rep(starters, each=rlen) + seq_len(rlen)
# or...
unlist(lapply(starters+1L,function(x)seq(x,x+rlen-1L)))
This can also be done using seq
or seq.int
x = c(1, 144, 288)
c(sapply(x, function(y) seq.int(y, length.out = 6)))
#[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
As @Frank mentioned in the comments here is another way to achieve this using @josilber's data structure (This is useful particularly when there is a need of different sequence length for different intervals)
c(with(info, mapply(seq.int, start, length.out=len)))
#[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293