Search code examples
rsortingrandommontecarlo

Group matching numbers in random order in R


I'm working on a Monte-Carlo simulation type problem and need to generate a vector of repeated random numbers, with the matching numbers grouped together, but in random order.

It's easier to explain with an example. If I had: 1, 3, 7, 12, 1, 3, 7, 12, 1, 3, 7, 12

I would like it sorted as: 7, 7, 7, 3, 3, 3, 12, 12, 12, 1, 1, 1 (or with the groups of matching numbers in any order but ascending/descending).

The reason I need the random order is because my MC simulation is for 2 variables, so if both are in order they won't vary independently.

I've got as far as:

sort(rep(runif(50,1,10),10), decreasing = FALSE)

Which generates 50 random numbers between 1 and 10, repeats each 10 times, then sorts the 50 groups of 10 matching random numbers in ascending order (or it could easily be descending order if I changed "FALSE" to "TRUE"). I just can't figure out the last step of getting 50 groups of 10 matching numbers in random order. Can anyone help?


Solution

  • Here is one option with split

    unlist(sample(split(v1, v1)), use.names = FALSE)
    #[1]  3  3  3  1  1  1 12 12 12  7  7  7
    

    Or another option is match with unique

    v1[order(match(v1, sample(unique(v1))))]
    

    data

    v1 <- c(1, 3, 7, 12, 1, 3, 7, 12, 1, 3, 7, 12)