首页 > 解决方案 > 如何对具有概率约束的向量进行伪随机化?

问题描述

我有数字 1 到 5。我需要每个数字出现 24 次(所以我的整个列表应该有 120 个数字)。我需要没有连续的重复(4 不能跟随 4)。我还需要每个数字在每次出现时只跟随对方的 25%(5 应该跟随 4 六次)。

我怎样才能在 R 中做到这一点?我尝试从 1 到 5 采样 24 次,然后对其进行排列,但必须有更聪明的方法!我感觉像是一个 for 循环之类的?我很茫然,觉得这是一个我没有看到的简单解决方案。

谢谢!

# There are 5 different items I am trying to order
   Trips = c(1:5)

# Each set of 5 needs to appear 24 times, so inefficiently making it 24 times 
  T1 <- sample(Trips, replace = FALSE)
  T2 <- sample(Trips, replace = FALSE)
  T3 <- sample(Trips, replace = FALSE)
  T4 <- sample(Trips, replace = FALSE)
  T5 <- sample(Trips, replace = FALSE)
  T6 <- sample(Trips, replace = FALSE)
  T7 <- sample(Trips, replace = FALSE)
  T8 <- sample(Trips, replace = FALSE)
  T9 <- sample(Trips, replace = FALSE)
  T10 <- sample(Trips, replace = FALSE)
  T11 <- sample(Trips, replace = FALSE)
  T12 <- sample(Trips, replace = FALSE)
  T13 <- sample(Trips, replace = FALSE)
  T14 <- sample(Trips, replace = FALSE)
  T15 <- sample(Trips, replace = FALSE)
  T16 <- sample(Trips, replace = FALSE)
  T17 <- sample(Trips, replace = FALSE)
  T18 <- sample(Trips, replace = FALSE)
  T19 <- sample(Trips, replace = FALSE)
  T20 <- sample(Trips, replace = FALSE)
  T21 <- sample(Trips, replace = FALSE)
  T22 <- sample(Trips, replace = FALSE)
  T23 <- sample(Trips, replace = FALSE)
  T24 <- sample(Trips, replace = FALSE)


# Combining the triplets made above into one stream
  Stream_T <- c(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, 
                T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24)


   df <- as.data.frame(Stream_T)

# Checking how often each number follows each other
  cbind(ahead = lead(df$Stream_T), df$Stream_T, behind = lag(df$Stream_T))

标签: rdplyr

解决方案


编辑:

虽然这不是一个解决方案(原因如下所示),但我将把它作为一个起点,以防其他人想要尝试一下。随意在评论中要求删除,我会这样做

由于您for在问题中提到了循环,因此这是使用循环的可能解决方案:

设置信息:

set.seed(124)
numbers <- c(1, 2, 3, 4, 5)
total_length <- 120

用第一个随机绘制的值初始化结果向量

result <- sample(numbers, 1)

现在迭代剩余的值,每次迭代都排除结果列表中的最后一个元素(所以我们不能绘制相同的数字)

for (i in 1:(total_length -1 )) {
  allowed <- numbers[numbers != result[length(result)]]
  result <- c(result, sample(allowed, 1))
}

结果应该具有所有所需的特征,但可能样本量太小,无法使用“大数定律”;)

让我们测试一下:

条件“我需要没有连续重复(4 不能跟随 4)”

all((lag(result,default = 10) - result) != 0)
all((lead(result,default = 10) - result) != 0)

两者都返回:

[1] TRUE

到目前为止一切顺利,但是:

条件“我需要每个数字出现 24 次”

table(result)

回报:

result
1  2  3  4  5 
24 26 24 25 21 

-> 条件不满足!


推荐阅读