将两列与ID组合在一起,对两列进行累计

时间:2017-06-16 14:17:28

标签: r cumsum

编辑:我写了一个非结构化的问题,让我再试一次。

我想为下面的数据集创建两个新列winner_total_pointsloser_total_points

winner <- c(1,2,3,4,1,2)
loser <- c(2,3,1,3,3,1)
winner_points <- c(5,4,12,2,1,6)
loser_points <- c(5,2,2,6,6,2)
test_data <- data.frame(winner, loser, winner_points, loser_points)

我希望这两个专栏要做的是winner_total_points将获胜者获得的所有积分(不包括此匹配)加为赢家和输家。

loser_total_points的功能与失败者相同。

请注意,winnerloser列包含相应的播放器ID。

现在,使用ave()函数相当容易,但这只适用于仅对列进行分组并对一列执行累计求和。

期望的输出:

winner loser winner_points loser_points winner_total loser_total
1      2     5             5            5            5
2      3     4             2            9 (5+4)      2
3      1     12            2            14 (2+12)    7 (5+2)
4      3     2             6            2            20 (2+12+6)
1      3     1             6            8 (5+2+1)    26 (2+12+6+6)
2      1     6             2            15 (5+4+6)   10 (5+2+1+2)

2 个答案:

答案 0 :(得分:1)

我也很难理解,但也许这个......?

users: (_, args, context, ast) => {
  const { onlyNonNullEmail } = args;

  // If onlyNonNullEmail is true, return only users with a non-null email
  // Else proceed as usual
}

答案 1 :(得分:0)

如果我正确理解了OP的要求,他想按玩家ID计算积分的累计总和,无论是wins_points还是loser_points。这里重点是要注意winnerloser列包含各自的玩家ID。

下面的解决方案将数据从宽格式转换为长格式,从而同时重塑两个值变量,计算每个玩家ID的累积总和,最后再次从长格式再格式化为宽格式。

library(data.table
cols <- c("winner", "loser")
setDT(test_data)[
  # append row id column required for subsequent reshaping
  , rn := .I][
    # reshape multiple value variables simultaneously from wide to long format
    , melt(.SD, id.vars = "rn", 
           measure.vars = list(cols, paste0(cols, "_points")), 
           value.name = c("id", "points"))][
             # rename variable column
             , variable := forcats::lvls_revalue(variable, cols)][
               # order by row id and compute cumulative points by id
               order(rn), total := cumsum(points), by = id][
                 # reshape multiple value variables simultaneously from long to wide format
                 , dcast(.SD, rn ~ variable, value.var = c("id", "points", "total"))]
   rn id_winner id_loser points_winner points_loser total_winner total_loser
1:  1         1        2             5            5            5           5
2:  2         2        3             4            2            9           2
3:  3         3        1            12            2           14           7
4:  4         4        3             2            6            2          20
5:  5         1        3             1            6            8          26
6:  6         2        1             6            2           15          10

编辑:以上结果与OP发布的预期结果一致。  它包括得分包括实际匹配。同时,the OP has posted a similar question预期结果排除实际匹配。

相关问题