Search code examples
rseqrep

Creating a (half-) regular sequence - a regular rate of varying intervals


I want to create a kind of nested regular sequence in R. It follows a repeating pattern, but without consistent intervals between values. It is:

8, 9, 10, 11, 12, 13, 17, 18, 19, 20, 21, 22, 26, 27, 28, ....

So 6 numbers with an interval of 1, then an interval of 3, and then the same again. I'd like to have this all the way up to about 200, ideally being able to specify that end point.

I have tried using rep and seq, but do not know how to get the regularly varying interval length into either function.

I started plotting it and thinking about creating a step function based on the the length... it can't be that difficult - what's the trick/magic package I don't know of??


Solution

  • Without doing any math to figure out how many groups and such, we can just over-generate.

    Defining terminology, I'll say you have a bunch of groups of sequences, with 6 elements per group. We'll start with 100 groups to make sure we definitely cross the 200 threshhold.

    n_per_group = 6
    n_groups = 100
    
    # first generate a regular sequence, with no adjustments
    x = seq(from = 8, length.out = n_per_group * n_groups)
    
    # then calculate an adjustment to add 
    # as you say, the interval is 3 (well, 3 more than the usual 1)
    adjustment = rep(0:(n_groups - 1), each = n_per_group) * 3
    
    # if your prefer modular arithmetic, this is equivalent
    # adjustment = (seq_along(x) %/% 6) * 3
    
    # then we just add
    x = x + adjustment
    
    # and subset down to the desired result
    x = x[x <= 200]
    
    x
    #  [1]   8   9  10  11  12  13  17  18  19  20  21  22  26  27  28  29  30
    # [18]  31  35  36  37  38  39  40  44  45  46  47  48  49  53  54  55  56
    # [35]  57  58  62  63  64  65  66  67  71  72  73  74  75  76  80  81  82
    # [52]  83  84  85  89  90  91  92  93  94  98  99 100 101 102 103 107 108
    # [69] 109 110 111 112 116 117 118 119 120 121 125 126 127 128 129 130 134
    # [86] 135 136 137 138 139 143 144 145 146 147 148 152 153 154 155 156 157
    #[103] 161 162 163 164 165 166 170 171 172 173 174 175 179 180 181 182 183
    #[120] 184 188 189 190 191 192 193 197 198 199 200