Generate a sequence of numbers with repeated intervals

32,671

Solution 1

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.

Solution 2

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)))

Solution 3

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

Solution 4

From R >= 4.0.0, you can now do this in one line with sequence:

sequence(c(6,6,6), from = c(1,144,288))
[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293

The first argument, nvec, is the length of each sequence; the second, from, is the starting point for each sequence.

As a function, with n being the number of intervals you want:

f <- function(n) sequence(rep(6,n), from = c(1,144*1:(n-1)))
f(3)
[1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293
Share:
32,671
giac
Author by

giac

PhD student.

Updated on July 09, 2022

Comments

  • giac
    giac almost 2 years

    I am trying to create sequences of number of 6 cases, but with 144 cases intervals.

    Like this one for example

    c(1:6, 144:149, 288:293)
    
    1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293
    

    How could I generate automatically such a sequence with

    seq 
    

    or with another function ?