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.
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 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.
Seq(): The seq function in R can generate the general or regular sequences from the given inputs.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With