Repeating a repeated sequence
Asked Answered
P

5

22

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?

Prerecord answered 24/6, 2012 at 18:32 Comment(1)
it thought about a for loop, but isnt there a simpler way?Prerecord
A
60

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
Aldred answered 24/6, 2012 at 21:20 Comment(0)
M
20

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

rep(rep(1:4,each=3),3)
Mannos answered 24/6, 2012 at 18:42 Comment(1)
Looking at this years later, I'm not sure that it is simpler, but I think a case could be made that it is more flexible in that you could use it to perform the "times" operation first to be followed by "each" processing.Aldred
D
9

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.

Dagger answered 20/6, 2018 at 15:56 Comment(1)
To further randomise the resulting vector (or change the order of the vector randomly), just do: sample(rep(seq(0,60,15), times = 3))Faqir
P
2

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.

Poppied answered 24/6, 2012 at 18:39 Comment(1)
You should take a look at Dieter's answer - the 'each' parameter would do what you're doing a lot nicer than using a call to sapply.Impressment
H
0

Here is a method using array manipulation with aperm. The idea is to construct an array containing the values. Rearrange them so they match the desired output using aperm, and then "unfold" the array with c.

c(aperm(array(1:4, dim=c(4,3,3)), c(2, 1, 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
Hesse answered 1/11, 2017 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.