根据平均分数挑选比赛冠军

时间:2019-11-05 15:07:24

标签: r

我正在尝试根据过去比赛的一组平均得分来模拟一个连续的单淘汰赛。

所需的最终结果是在新数据框中显示结果的括弧,其中包括每场比赛中有哪些球队出战,哪些球队获胜。

到目前为止,我已经尝试使用顺序for循环来做到这一点,但是我的代码只会变得越来越混乱。

library(reshape2) # for melt

x <- 4 # number of teams in the tournament
y <- 3 # number of tournaments
set.seed(123)
# generate the order teams play in, each row is a separate, independent tournament
combos <- sample(1:x, x, replace = FALSE) 
for (i in 2:y) combos <- rbind(combos, sample(1:x, x, replace = FALSE))
row.names(combos) <- NULL # resets numbering in row names

reshaped <- melt(combos)
names(reshaped) <- c("Tournament", "Game", "Team")
reshaped <- reshaped[order(reshaped$Tournament),]

# generate average scores to use to pick new tournament winners
abilities <- matrix(rnorm(x*y, mean = 95, sd = 10), ncol = x, nrow = y)
colnames(abilities) <- paste0("Team", 1:x)

reshaped$Avg.Score <- mapply("[", list(abilities), reshaped$Tournament, reshaped$Team)

# Below is the desired result (hard coded)
# It keeps track of the tournament number, which team was first and second
# (order doesn't matter, as long as it is "new entrant" and "previous winner"), 
# and which team won that game 
# (no need to include the scores, I included them here for reference to make it clear)

bracket <- data.frame(Tournament = c(1, 1, 1, 2, 2, 2, 3, 3, 3), 
                      FirstTeam = c(3, 4, 4, 3, 2, 2, 3, 1, 2), 
                      SecondTeam = c(4, 1, 2, 2, 4, 1, 1, 2, 4), 
                      Winner = c(4, 4, 4, 2, 2, 2, 3, 2, 2))
bracket$score1 <- mapply("[", list(abilities), bracket$Tournament, bracket$FirstTeam)
bracket$score2 <- mapply("[", list(abilities), bracket$Tournament, bracket$SecondTeam)

> bracket
  Tournament FirstTeam SecondTeam Winner    score1    score2
1          1         3          4      4  99.00771 112.86913
2          1         4          1      4 112.86913  99.60916
3          1         4          2      4 112.86913  90.54338
4          2         3          2      2  96.10683 107.24082
5          2         2          4      2 107.24082  99.97850
6          2         2          1      2 107.24082  82.34939
7          3         3          1      3  89.44159  88.13147
8          3         1          2      2  88.13147  98.59814
9          3         2          4      2  98.59814  75.33383

0 个答案:

没有答案