Search code examples
rsequenceseriesseqrep

Generate series 1, 2,1, 3,2,1, 4,3,2,1, 5,4,3,2,1


I am trying to generate a vector containing decreasing sequences of increasing length, such as 1, 2,1, 3,2,1, 4,3,2,1, 5,4,3,2,1, i.e.

c(1, 2:1, 3:1, 4:1, 5:1)

I tried to use a loop for this, but I don't know how to stack or concatenate the results.

for (i in 1:11)
 {
 x = rev(seq(i:1))
 print(x) 
 }
[1] 1
[1] 2 1
[1] 3 2 1
[1] 4 3 2 1
[1] 5 4 3 2 1
[1] 6 5 4 3 2 1
[1] 7 6 5 4 3 2 1
[1] 8 7 6 5 4 3 2 1
[1] 9 8 7 6 5 4 3 2 1
[1] 10  9  8  7  6  5  4  3  2  1
[1] 11 10  9  8  7  6  5  4  3  2  1

I have also been experimenting with the rep, rev and seq, which are my favourite option but did not get far.


Solution

  • With sequence:

    rev(sequence(5:1))
    # [1] 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
    

    From R 4.0.0 sequence takes arguments from and by:

    sequence(1:5, from = 1:5, by = -1)
    # [1] 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
    

    Far from the golf minimalism of rev... However, if you wake up one morning and want to create such a sequence with n = 1000 (like in the answer below), the latter is in fact faster (but I can hear Brian Ripley in fortunes::fortune(98))

    n = 1000
    
    microbenchmark(
      f_rev = rev(sequence(n:1)),
      f_seq4.0.0 = sequence(1:n, from = 1:n, by = -1))
    # Unit: microseconds
    #        expr   min     lq     mean  median     uq    max neval
    #       f_rev 993.7 1040.3 1128.391 1076.95 1133.3 1904.7   100
    #  f_seq4.0.0 136.4  141.5  153.778  148.25  150.1  304.7   100