【问题标题】:Draw from a bag of colored marbles; for each draw remove all marbles of that color从一袋彩色弹珠中画画;对于每次抽奖,删除该颜色的所有弹珠
【发布时间】:2018-08-04 16:47:18
【问题描述】:

我想按照一些简单的规则从一袋彩色弹珠中抽出,无需更换。有多个相同颜色的弹珠(例如,5 个蓝色、3 个红色、7 个黄色、4 个绿色)。假设我画了 3 个弹珠,一次一个弹珠。每次抽奖后,我都会删除该颜色的所有弹珠。例如,我选择一个绿色,我从袋子中取出所有绿色弹珠;我选择一个红色,我从袋子里取出所有红色弹珠,等等。

我不完全清楚如何最有效地删除与焦点绘制相同颜色的所有弹珠,而无需大量的 for 循环。下面的虚拟代码仅根据绘制向量绘制弹珠。

#Dummy code
set.seed(123)
multiple_draws <- c(3,2,4,1)
bag <- c(rep("blue",5),rep("red",3),rep("yellow",7),rep("green",4))

sapply(seq(length(multiple_draws)), function(i) sample(bag, multiple_draws[i],replace=F), simplify=F) 

任何指针将不胜感激。

【问题讨论】:

  • @www 抱歉,已修复

标签: r list vector dplyr sample


【解决方案1】:

我会去做类似的事情

for(draw in multiple_draws){
  if(length(bag)>draw){
  color <- unique(sample(bag, draw,replace=F))
  bag <- bag[!bag %in% color]}
}

你实际上做了你想做的事:你删除了所有由bag &lt;- bag[!bag %in% color]绘制的大理石color

我放了一个if语句,因为我不知道如果抽奖次数高于弹子数,你想做什么。

【讨论】:

    【解决方案2】:

    我们可以设计一个函数来完成采样任务。每次采样后,bag &lt;- bag[!bag %in% s] 会完全去除该颜色。

    # Dummy code
    set.seed(123)
    multiple_draws <- c(3, 2, 4, 1) # No draw is larger than 4
    bag <- c(rep("blue",5),rep("red",3),rep("yellow",7),rep("green",4))
    
    # A function for sampling
    sample_fun <- function(draw, bag){
      ans <- numeric()
      for (i in 1:draw){
        s <- sample(bag, 1, replace = FALSE)
        bag <- bag[!bag %in% s]
        ans[i] <- s
      }
      return(ans)
    }
    
    # Apply the function through multiple_draws
    lapply(multiple_draws, sample_fun, bag = bag)
    # [[1]]
    # [1] "red"   "green" "blue" 
    # 
    # [[2]]
    # [1] "green"  "yellow"
    # 
    # [[3]]
    # [1] "blue"   "yellow" "green"  "red"   
    # 
    # [[4]]
    # [1] "yellow"
    

    【讨论】:

      【解决方案3】:

      您的数据

      set.seed(123)
      multiple_draws <- c(3,2,4,1)
      bag <- c(rep("blue",5),rep("red",3),rep("yellow",7),rep("green",4))
      

      使用prop.table(table(...))将您的向量转换为比例表

      prop.table(table(bag))
      
      # bag
           # blue     green       red    yellow 
      # 0.2631579 0.2105263 0.1578947 0.3684211
      

      您可以对 bag 中的唯一值进行采样,将概率设置为比例

      custom_sample <- function(vec, T) {
          sample(names(prop.table(table(vec))), T, replace=FALSE, prob=prop.table(table(vec)))
      }
      lapply(multiple_draws, function(T) custom_sample(bag, T))
      # [[1]]
      # [1] "yellow" "red"    "blue"  
      
      # [[2]]
      # [1] "red"   "green"
      
      # [[3]]
      # [1] "yellow" "green"  "red"    "blue"  
      
      # [[4]]
      # [1] "blue"
      

      【讨论】:

      • 谢谢,这是最快的方法!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多