代码之家  ›  专栏  ›  技术社区  ›  Emily Kothe

计算组中行之间的差异分数

  •  1
  • Emily Kothe  · 技术社区  · 7 年前

    我可以得到第二队的得分差(在diff列中),但是我不知道如何计算 第一 团队。它应该是第二个团队的目标差的倒数(即在样本数据集中“种植者”应该拥有 1 -1

    library(dplyr)
    
    dat <-
      structure(
        list(
          Match = c(1, 1, 2, 2, 3, 3),
          Team = c("Growlers",
                   "Rollers", "Strike", "Bandits", "Cats", "Blues"),
          Goals = c(1,0, 0, 1, 1, 2)
        ),
        row.names = c(NA,-6L),
        groups = structure(
          list(
            Match = c(895825, 895826, 895827),
            .rows = list(1:2, 3:4,
                         5:6)
          ),
          row.names = c(NA,-3L),
          class = c("tbl_df", "tbl",
                    "data.frame"),
          .drop = TRUE
        ),
        class = c("grouped_df", "tbl_df",
                  "tbl", "data.frame")
      )
    
    dat %>% 
        group_by(Match) %>% 
        mutate(diff = Goals - lag(Goals))
    #> # A tibble: 6 x 4
    #> # Groups:   Match [3]
    #>   Match Team     Goals  diff
    #>   <dbl> <chr>    <dbl> <dbl>
    #> 1     1 Growlers     1    NA
    #> 2     1 Rollers      0    -1
    #> 3     2 Strike       0    NA
    #> 4     2 Bandits      1     1
    #> 5     3 Cats         1    NA
    #> 6     3 Blues        2     1
    

    创建于2019-02-26 reprex package

    0 回复  |  直到 7 年前
        1
  •  1
  •   Andrie    7 年前

    一种快速而肮脏的方法是显式计算团队1和团队2的分数,如下所示:

    dat %>% 
      group_by(Match) %>% 
      mutate(
        diff = c(
          Goals[1] - Goals[2],
          Goals[2] - Goals[1] 
        )
      )
    
    #> # A tibble: 6 x 4
    #> # Groups:   Match [3]
    #>   Match Team     Goals  diff
    #>   <dbl> <chr>    <dbl> <dbl>
    #> 1     1 Growlers     1     1
    #> 2     1 Rollers      0    -1
    #> 3     2 Strike       0    -1
    #> 4     2 Bandits      1     1
    
    推荐文章