r - 复制与前一行相反的数据帧行
问题描述
我有一些 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
解决方案
您可以创建相反的数据框并将其绑定到原始数据框。
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))
推荐阅读
- php - 在 WordPress 挂钩中设置超时
- python - 如何从两个列表中构造一个字典,将该键映射到python中值列表中相应索引处的值
- javascript - 如何从 javascript 中的 API 中提取图像 ID?
- python - rx.interval 和 rx.timer 不产生结果
- python - 正则表达式日志解析 - 如何在一个事件中开始解析行并在另一个事件中停止解析行?
- c# - 使用 ADO.NET DataReader 和 Web 套接字进行延迟加载
- c# - 创建命名参数的 C# 控制台 exe 程序
- python - 有没有办法检查 MySQL 字典的元素是否包含特定的整数?
- node.js - 托管 NodeJs 应用程序
- python - Django view get() 接受 1 个位置参数,但给出了 2 个