You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中随机排列重复随机数分组的实现方法

Solution for Random Grouped Repeated Random Numbers in Monte Carlo Simulation

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:

  1. Generate your 50 unique random values between 1 and 10:
    unique_rands <- runif(50, 1, 10)
    
  2. Shuffle these unique values to get a random group order:
    shuffled_rands <- sample(unique_rands)
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:09:47