Replicate rows of data frame with inverse of previous row

Viewed 34

I have some NCAA basketball game-by-game final score data. Each row represents 1 game. But I would like to also have the "inverse" of each record. Meaning if drake is the "team" in row 1, then air force would be the "team" in row 2 with drake being the opponent, etc.

My data looks like:

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

But I only have one record for each game. I would like for each game_id to have 2 records. One also containing the "inverse".

# 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
1 Answers

You can create the opposite dataframe and bind it to original one.

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

In base 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))
Related