R语言中随机排列重复随机数分组的实现方法
Hey there! I get exactly what you need for your Monte Carlo simulation—you want groups of repeated random numbers where the order of the groups is random (not sorted), so your two variables stay independent. Let's fix your code step by step.
The Problem with Your Current Code
Your current line sort(rep(runif(50,1,10),10), decreasing = FALSE) first repeats each random number, then sorts the whole vector. That forces the groups to be in ascending order, which breaks the independence you need for your simulation.
The Fix: Shuffle First, Then Repeat
The key is to randomize the order of your unique random values before repeating them. Here's how to do it clearly:
- Generate your 50 unique random values between 1 and 10:
unique_rands <- runif(50, 1, 10) - Shuffle these unique values to get a random group order:
shuffled_rands <- sample(unique_rands) - Repeat each shuffled value 10 times consecutively:
final_vector <- rep(shuffled_rands, each = 10)
Simplified One-Liner
You can condense this into a single clean line if you prefer:
final_vector <- rep(sample(runif(50, 1, 10)), each = 10)
Why This Works
sample(unique_rands)randomly reorders your 50 unique numbers, so the groups will appear in a totally random sequence (no ascending/descending bias at all).- Using
rep(..., each = 10)ensures each number is repeated 10 times in a row, keeping identical values grouped together exactly like your example (7,7,7,3,3,3,12,12,12,1,1,1).
This structure maintains the grouped repeated values you need while ensuring group order is random—perfect for keeping your simulation variables independent.
内容的提问来源于stack exchange,提问作者TimM

