Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through numbers using seq() and rep()

Tags:

r

I need to use rep() and seq() to get the following vector:

1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 

Normally I would just use a for statement to achieve this but I am restricted from using that and can only use rep() and seq() to achieve this vector.

like image 526
turner Avatar asked Feb 13 '23 20:02

turner


2 Answers

> 1:5 + rep(0:4, each=5)
 [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
like image 190
Julián Urbano Avatar answered Feb 19 '23 18:02

Julián Urbano


One liner,

do.call(c,sapply(1:5,seq,length.out=5,simplify=FALSE))

Or even simpler,

rep(seq(5),each=5)+seq(5)-1
like image 22
xb. Avatar answered Feb 19 '23 19:02

xb.