简体   繁体   中英

How to create a sequence of sequences of numbers in R?

I would like to make the following sequence in R, by using rep or any other function.

[1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5]

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

Use sequence .

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

The first argument, nvec , is the length of each sequence ( 5:1 ); the second, from , is the starting point for each sequence ( 1:5 ).

Note : this works only for R >= 4.0.0. From R News 4.0.0 :

sequence() [...] gains arguments [eg from ] to generate more complex sequences.

unlist(lapply(1:5, function(i) i:5))
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5

Your mention of rep reminded me of replicate , so here's a very stateful solution. I'm presenting this because it's short and unusual, not because it's good. This is very unidiomatic R.

vect <- 0:5
unlist(replicate(5, vect <<- vect[-1]))
[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5

You can do it with a combination of rep and lapply , but it's basically the same as Merijn van Tilborg's answer.

Here's an example of how not to do it:

out=c();for(i in 1:5){ out=c(out, (1:5)[i:5]) }
out
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM