【问题标题】:R Looping: Assign record to class with least existing recordsR循环:将记录分配给现有记录最少的类
【发布时间】:2018-08-18 03:04:42
【问题描述】:

我有一组个人,我正在向他们分发物品,以努力实现在个人之间平均分配总物品。

每个人只能收到特定类型的物品。

物品的起始分布不均等。

每种类型的可用物品数量是已知的,并且必须完全用尽。

df 包含人员数据的示例格式。请注意,Chuck 总共有 14 件物品,而不是 14 个球棒和 14 个手套。

df<-data.frame(person=c("Chuck","Walter","Mickey","Vince","Walter","Mickey","Vince","Chuck"),alloweditem=c("bat","bat","bat","bat","ball","ball","glove","glove"),startingtotalitemspossessed=c(14,9,7,12,9,7,12,14))

otherdf 包含需要分配的项目和编号的示例格式

otherdf<-data.frame(item=c("bat","ball","glove"),numberneedingassignment=c(3,4,7))

有没有最好的方法来编码这种形式的项目分布?我想的步骤是:

  1. 检查可以接收给定项目的人分配的项目总数最少。随意打破平局。

  2. 将给定项目的 1 个分配给此人。

  3. 更新收货人的startingtotalitemspossessed

  4. 更新剩余待分配项目的编号。

  5. 如果剩余总数为 0,则停止给定项目的循环,并移至下一个项目。

下面是部分表示,就像我想象的那样,它是循环内的一个视图,从左到右。

注意:物品数量和人数非常多。如果可能的话,一种可以扩展到任何给定数量的人或物品的方法将是理想的!

提前感谢您的帮助!

【问题讨论】:

标签: r


【解决方案1】:

我确信有更好的方法,但这里有一个例子:

df<-data.frame(person=c("Chuck","Walter","Mickey","Vince","Walter","Mickey","Vince","Chuck"),
    alloweditem=c("bat","bat","bat","bat","ball","ball","glove","glove"),
    total=c(14,9,7,12,9,7,12,14))
print(df)
##   person alloweditem total
## 1  Chuck         bat    14
## 2 Walter         bat     9
## 3 Mickey         bat     7
## 4  Vince         bat    12
## 5 Walter        ball     9
## 6 Mickey        ball     7
## 7  Vince       glove    12
## 8  Chuck       glove    14

otherdf<-data.frame(item=c("bat","ball","glove"),
    numberneedingassignment=c(3,4,7))

# Items in queue
queue <- rep(otherdf$item, otherdf$numberneedingassignment)

for (i in 1:length(queue)) {
  # Find person with the lowest starting total
    personToBeAssigned <- df[df$alloweditem == queue[i] & 
    df$total == min(df[df$alloweditem == queue[i], 3]), 1][1]
    df[df$person == personToBeAssigned & df$alloweditem == queue[i], 3] <- 
      df[df$person == personToBeAssigned & df$alloweditem == queue[i], 3] + 1
}

print(df)
##   person alloweditem total
## 1  Chuck         bat    14
## 2 Walter         bat    10
## 3 Mickey         bat     9
## 4  Vince         bat    12
## 5 Walter        ball    10
## 6 Mickey        ball    10
## 7  Vince       glove    17
## 8  Chuck       glove    16

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多