使用前一行的倒数复制数据框的行

Replicate rows of data frame with inverse of previous row

我有一些 NCAA 篮球逐场比赛的最终得分数据。每行代表一场比赛。但我也想拥有每条记录的“逆”。这意味着如果德雷克是第 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

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

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))