Repeating a repeated sequence

Fabian Stolz picture Fabian Stolz · Jun 24, 2012 · Viewed 29.8k times · Source

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?

Answer

IRTFM picture IRTFM · Jun 24, 2012

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)
#[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