首页 > 解决方案 > 复制与前一行相反的数据帧行

问题描述

我有一些 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

标签: rdplyrtidyversedata-manipulation

解决方案


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

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

推荐阅读