【问题标题】:How to simulate a vector only contains 0, 1, 2 with given sum of the vector如何模拟一个向量只包含 0、1、2 和给定的向量总和
【发布时间】:2019-07-18 05:52:22
【问题描述】:

我将在 R 中模拟一个包含 100 个元素的向量。该向量仅包含数值 0、1 或 2。我只知道向量的总和。例如,如果向量的和是30,0的总数可以是77,1的总数可以是16,2的总数可以是7。我如何在R中模拟这样的向量基于向量的和?

【问题讨论】:

  • 你还能得到 sum = 77 和 0 = 0 , 1 = 77, 2 = 0 的数字吗?
  • 您是否只是希望找到 一个 组合以使总和正确?如果是这样,那么这样一个过程的运行时间是不确定的......虽然不太可能,但它可能会运行很长时间才能找到一个。
  • 只是好奇,这是作业吗?没有规则反对它,但它可以影响我们的回答方式。 (让我们完全为你解决你的家庭作业对你来说确实是一种伤害。)
  • 你有没有尝试过,Mizzle?我认为这可以通过 whilesumsample 的直接组合来完成,也许可以使用内置计数器来永久排除搜索。
  • 我认为这个问题很有趣,可能需要一个聪明而新颖的解决方案。基于sample 的简单解决方案在某些限制条件下可以正常工作,但我认为仅通过简单抽样就很难满足其他条件。

标签: r


【解决方案1】:

这是解决此问题的一个非常简单的尝试。它不是对所有 100 个元素进行采样,而是利用必须至少有 100 - target 零的事实。我认为可能还有一种方法可以利用最多有100 - (target / 2) 零的事实(如果所有非零元素都是 2)。

sim_freq = function(target, total_size = 100, max_attempts = 100) {

   min_zeros = total_size - target 

   target_found = FALSE 
   attempts = 0
   while (! target_found) {
       alleles = sample(0:2, size = target, replace = TRUE)
       target_found = sum(alleles) == target
       attempts = attempts + 1

       if (attempts > max_attempts) {
           stop("Couldn't find a match")
       }
   }

   print(paste0("Found a match in ", attempts, " attempts."))
   # Shuffle the generated alleles and zeros together
   sample(c(alleles, rep(0, min_zeros)))
}

用法:

sim_freq(26)
sim_freq(77)

在我的目标为 26 和 77 的测试运行中,它通常会在

【讨论】:

  • 非常感谢!我认为这是最好的答案。
【解决方案2】:

这里你有一些代码来做,我做了 15 个元素来更快地计算它:

x <- 0:2 #values you desire in the vector
y <- 10  #desired sum of the vector
b <- 0  #inizialize b
#until the sum of the elements is equal to the desired sum
while (b != y) {
  a = sample(x,15,replace = TRUE) #calculate a random vector of 15 elements
  b = sum(a) #sum of the elements
}
a #desired vector

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2020-12-18
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多