Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 450
FFB Avatar asked Mar 28 '17 08:03

FFB


People also ask

How do I create a series in R?

The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).

How do I generate a list of numbers in R?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.

Which function is used to generate sequences in R?

Seq(): The seq function in R can generate the general or regular sequences from the given inputs.

How do you repeat numbers in R?

How do you Repeat a Sequence of Numbers in R? To repeat a sequence of numbers in R you can use the rep() function. For example, if you type rep(1:5, times=5) you will get a vector with the sequence 1 to 5 repeated 5 times.


1 Answers

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 
like image 172
Henrik Avatar answered Sep 27 '22 21:09

Henrik