Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a repeated sequence

We want to get an array that looks like this:

1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4

What is the easiest way to do it?

like image 341
Fabian Stolz Avatar asked Jun 24 '12 18:06

Fabian Stolz


4 Answers

You can do it with a single rep call. The each and times parameters are evaluated sequentially with the each being done first.

rep(1:4, times=3, each=3)  # 'each' done first regardless of order of named parameters
#[1] 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4
like image 62
IRTFM Avatar answered Oct 20 '22 21:10

IRTFM


Or, simpler (assuming you mean a vector, not an array)

rep(rep(1:4,each=3),3)
like image 19
Dieter Menne Avatar answered Oct 20 '22 21:10

Dieter Menne


42-'s answer will work if your sequence of numbers incrementally increases by 1. However, if you want to include a sequence of numbers that increase by a set interval (e.g. from 0 to 60 by 15) you can do this:

rep(seq(0,60,15), times = 3)
[1]  0 15 30 45 60  0 15 30 45 60  0 15 30 45 60  

You just have to change the number of times you want this to repeat.

like image 8
TheSciGuy Avatar answered Oct 20 '22 20:10

TheSciGuy


Like this:

rep(sapply(1:4, function(x) {rep(x, 3)}), 3)

rep(x, N) returns a vector repeating x N times. sapply applies the given function to each element of the vector 1:4 separately, repeating each element 3 times consecutively.

like image 2
Stef Sijben Avatar answered Oct 20 '22 19:10

Stef Sijben