【问题标题】:Replicate rows of data frame with inverse of previous row复制与前一行相反的数据帧行
【发布时间】:2021-12-23 15:06:28
【问题描述】:

我有一些 NCAA 篮球逐场比赛的最终得分数据。每行代表 1 场比赛。但我也想拥有每条记录的“逆”。这意味着如果德雷克是第 1 行中的“团队”,那么空军将是第 2 行中的“团队”,而德雷克是对手,等等。

我的数据如下:

game_id   team       opp       team_score   opp_score   score_diff favored_by  line
  1       drake       air force 81           53          28         11          125
  2       cincinatti  usf       71           74          -3         8.5         132

但我每场比赛只有一个记录。我希望每个 game_id 有 2 条记录。一个还包含“逆”。

# Desired output:
 game_id   team       opp       team_score   opp_score   score_diff favored_by line
  1       drake       air force  81         53            28           11      125
  1       air force   drake      53         81           -28          -11      125
  2       cincinatti  usf        71         74           -3            8.5     132
  2       usf         cincinatti 74         71            3           -8.5     132

【问题讨论】:

    标签: r dplyr tidyverse data-manipulation


    【解决方案1】:

    您可以创建相反的数据框并将其绑定到原始数​​据框。

    library(dplyr)
    
    df %>%
      mutate(opp = team, 
             team = .$opp, 
             team_score = opp_score, 
             opp_score = .$team_score, 
             score_diff = -score_diff, 
             favored_by = -favored_by) %>%
      bind_rows(df) %>%
      arrange(game_id)
    
    #  game_id       team        opp team_score opp_score score_diff favored_by line
    #1       1   airforce      drake         53        81        -28      -11.0  125
    #2       1      drake   airforce         81        53         28       11.0  125
    #3       2        usf cincinatti         74        71          3       -8.5  132
    #4       2 cincinatti        usf         71        74         -3        8.5  132
    

    在基础 R 中 -

    rbind(df, transform(df, opp = team, team =  opp, 
              team_score = opp_score, opp_score = team_score, 
              score_diff = -score_diff, 
              favored_by = -favored_by))
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2021-11-20
      • 2018-11-19
      • 2015-09-08
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多