dwenzel
dwenzel

Reputation: 99

Generating a vector with random numbers repeated 'n' times

In RCode, How to generate a vector with 1000 values, with randomic numbers between 1:3, but each value repeat "n" times in sequence?

I know that

sample(1:3,1000, replace=TRUE)

will generate 1000 values ranging between 1 and 3, but I need each value to repeat, for example, 5 times. Like below:

[1] 2 2 2 2 2 3 3 3 3 3 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1 3 3 3 3 3
.
.
.

Upvotes: 2

Views: 1407

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Here is another option using kronecker produce

kronecker(sample(1:3,1000,replace = TRUE),rep(1,5))

Upvotes: 2

akrun
akrun

Reputation: 887851

We can use the rep with each

rep(sample(1:3, 1000, replace = TRUE), each = 5)

Upvotes: 3

Duck
Duck

Reputation: 39613

Try this:

rep(sample(1:3,1000, replace=TRUE),each=5)

Upvotes: 3

Related Questions