r - 在调整“关系”时在 R 中加入表格
问题描述
我正在开展一个项目,该项目分析参加一系列比赛的人的投资回报率。对于每场比赛,我都有一个包含每个人排名的表格,以及另一个包含给定排名范围的支出的表格。我想加入这两个表,以根据每个人的排名为每个人分配奖金,但我在思考如何处理平局时遇到了问题。如果两个人并列,则平均支付。我的表有数十万个,所以我想为这个较小的例子正确处理这个过程。
排名表示例:
id rank
1 A 1
2 B 1
3 C 3
4 D 4
5 E 4
6 F 4
7 G 7
8 H 8
9 I 9
10 J 10
支付表示例:
rankMin rankMax payout
1 1 1 100
2 2 3 70
3 4 5 50
4 6 8 20
5 9 10 0
最终目标:
id rank payout
1 A 1 85 # Two people tied for first, so take average of 1st and 2nd payouts
2 B 1 85
3 C 3 70
4 D 4 40 # Three people tied for 4th, so take average of 4th/5th/6th payouts.
5 E 4 40
6 F 4 40
7 G 7 20
8 H 8 20
9 I 9 0
10 J 10 0
到目前为止我的代码:
# Load libraries
library(dplyr)
# Setup the rank table
id <- LETTERS[1:10]
rank <- c(1, 1, 3, 4, 4, 4, 7, 8, 9, 10)
finalStandingsDf <- data.frame(id, rank, stringsAsFactors = FALSE)
# Setup the payout table
rankMin <- c(1, 2, 4, 6, 9)
rankMax <- c(1, 3, 5, 8, 10)
payoutAmt <- c(100, 70, 50, 20, 0)
payoutDf <- data.frame(rankMin, rankMax, payoutAmt)
# "Unzip" the payout table to make it easier to join onto rank table
payoutsFixedAll <- data.frame()
for(i in 1:length(id)){
rank <- i
payoutIndex <- min(which(rank <= rankMax))
payout <- payoutDf[payoutIndex, 3]
payoutsFixed <- data.frame(rank, payout)
payoutsFixedAll <- rbind(payoutsFixedAll, payoutsFixed)
}
### Intermittent step to adjust the payoutsFixedAll table to account for ties ###
# Join onto rank table
rankPayoutDf <- finalStandingsDf %>%
left_join(payoutsFixedAll, by = c('rank'))
显然,我需要对支付表进行某种调整,以便正确调整,但我正在努力想出最好的方法。我认为这将涉及计算每个等级的数量(1:2、2:0、3:1、4:3等)并以某种方式从那里进行调整?我得到了需要做的事情我只是在努力寻找到达那里的道路。有什么想法吗?
解决方案
对于这个特定的数据集,我们可以 1)为每个排名进行支付,payoutDf
然后 2)根据 的排名平均支付finalStandingsDf
。
payouts = with(payoutDf, rep(payoutAmt, rankMax - rankMin + 1))
finalStandingsDf$payout <- ave(payouts, finalStandingsDf[["rank"]])
finalStandingsDf
id rank payout
1 A 1 85
2 B 1 85
3 C 3 70
4 D 4 40
5 E 4 40
6 F 4 40
7 G 7 20
8 H 8 20
9 I 9 0
10 J 10 0
推荐阅读
- java - 当我将扫描仪对象分配给变量时程序崩溃
- python - 即使数组长度相同,matplotlib 中的 ValueError
- django - 尝试在 Heroku 上收集静态文件时没有这样的文件或目录
- node.js - Node.js 的 GoogleAPIs,如何在没有浏览器和人工交互的情况下在服务器上对用户进行 oauth2
- sql - 根据其他日期字段的间隔更新日期字段
- swift - 委托方法:AVSpeechSynthesizerDelegate 的“willSpeakRangeOfSpeechString”未被调用
- git - Docker 上的 Jenkins 无法从 GitLab 克隆存储库,返回状态码 128
- material-ui - Material-ui 主题不会自动应用在 AppBar 上?
- eclipse - Maven Java Jersey Rest:未找到提供程序类。(访问 URL 时出现 404 错误)
- hyperledger-fabric - 需要但不支持通道功能 V1_3:在 Hyperledger Fabric 中制作我的第一个网络