【问题标题】:R multiplying cell wise without inefficient loopsR 在没有低效循环的情况下按单元格乘法
【发布时间】:2016-01-18 15:26:39
【问题描述】:

我有以下数据集结构,其中每个条目是该球队得分那么多分的概率(例如,球队在第 1 场比赛中得分 1 分的概率是 0.1)。

library(data.table)

x = data.table(matrix(c('game_1', 'team_a', 0.1, 0.2, 0.6, 0.1, 'game_1', 'team_b', 0.2, 0.3, 0.4, 0.1,
                        'game_2', 'team_a', 0.2, 0.1, 0.5, 0.2, 'game_2', 'team_b', 0.3, 0.2, 0.3, 0.2), ncol=6, byrow=T))
names(x) = c('game_number', 'team', 'point_1', 'point_2', 'point_3', 'point_4')

x

#    game_number   team point_1 point_2 point_3 point_4
# 1:      game_1 team_a     0.1     0.2     0.6     0.1
# 2:      game_1 team_b     0.2     0.3     0.4     0.1
# 3:      game_2 team_a     0.2     0.1     0.5     0.2
# 4:      game_2 team_b     0.3     0.2     0.3     0.2

我想知道每支球队赢得每场比赛的概率(以及每场比赛平局的概率)。有没有办法在没有大而低效的循环的情况下做到这一点?

例如团队获胜的概率 1:

= 0.1*0.4 + 0.1*0.3 + 0.1*0.2 + 0.6*0.3 + 0.6*0.2 + 0.2*0.2

【问题讨论】:

  • 没有按照您提供的数据集计算“球队获胜的概率 1”的示例。

标签: r loops


【解决方案1】:

我不知道执行此操作的好函数,但这是我将如何解决它。请注意,我只为此使用概率数据。此外,此脚本适用于任意数量的匹配项和任意数量的点。

library(data.table)
x = data.table(matrix(c('game_1', 'team_a', 0.1, 0.2, 0.6, 0.1, 'game_1', 'team_b', 0.2, 0.3, 0.4, 0.1,
                        'game_2', 'team_a', 0.2, 0.1, 0.5, 0.2, 'game_2', 'team_b', 0.3, 0.2, 0.3, 0.2), ncol=6, byrow=T))
names(x) = c('game_number', 'team', 'point_1', 'point_2', 'point_3', 'point_4')

x[, point_1 := as.numeric(point_1)]
x[, point_2 := as.numeric(point_2)]
x[, point_3 := as.numeric(point_3)]
x[, point_4 := as.numeric(point_4)]

x2 <- x
x2[, c('game_number','team') := NULL]

所以首先,我们要计算累积概率

# Calculate the cumulative probability
y <- t(apply(x2,1,cumsum))

从那时起,我们想将累积概率乘以对方球队的相应得分概率。

# Remove the 1 probability column in the end
y <- y[, -ncol(y)]

# Swap every odd with every subsequent even row
even <- seq(2, nrow(y), by=2)
sequence <- c(rbind(even,even-1))
y <- y[sequence,]

# Multiply the two vectors with each other
x2[, point_1 := NULL]
z <- x2 * y

最后,我们更新 x 以包含一个列 prob,该列将包含球队赢得那场比赛的概率。

# Find the probability of winning
x[, prob := rowSums(z)]

【讨论】:

猜你喜欢
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多