Dr. Manhattan Dr. Manhattan - 1 month ago 9
R Question

How to randomise a vector and keep the frequency of the elements fixed?

Extending this former question, how can I shuffle (randomize) the following vector

a1 = [1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5, 5]


in order to get something like this:

a2 = [5, 5, 3, 3, 3, 3, 1, 1, 2, 4, 4, 4]


or even better like this:

a3 = [4, 4, 4, 2, 3, 3, 3, 3, 1, 1, 5, 5]?


such that each element could randomly change to another but with keeping the number of each element constant?

Answer

You can try something like this: create a factor from a1 with randomly shuffled levels and then convert it to integers:

as.integer(factor(a1, levels = sample(unique(a1), length(unique(a1)))))
# [1] 5 5 4 4 4 4 3 3 2 1 1 1