我需要使用现有数据帧的行中包含的信息来创建多个数据帧。该过程应该不太困难,但是要简单地描述它并不容易。取以下数据框:
B <- data.frame(Player=c("a","b","c","d","e","f","a","b","c","d","e"),
Team=c("Red","Red","Light","Light","Blue","Blue","Red","Blue","Red","Blue","Light"),
Day=c("Monday","Monday","Monday","Monday","Monday","Monday","Tuesday","Tuesday","Tuesday","Tuesday","Tuesday"),
Result=c("Lose","Lose","Win","Win","Lose","Lose","Lose","Win","Lose","Win","Lose"))
B
Player Team Day Result
1 a Red Monday Lose
2 b Red Monday Lose
3 c Light Monday Win
4 d Light Monday Win
5 e Blue Monday Lose
6 f Blue Monday Lose
7 a Red Tuesday Lose
8 b Blue Tuesday Win
9 c Red Tuesday Lose
10 d Blue Tuesday Win
11 e Light Tuesday Lose
我需要为每个Player
(a,b,c等)创建一个新的数据框。新数据帧的列包括Team
,Day
,Result
,然后在总池中每隔Player
个列,其值指示是否该玩家是队友(1),对手(-1)或当天没有比赛(NA)。结果看起来像这样:
Player Day Team Result Team_mate_b Team_mate_c Team_mate_d Team_mate_e Team_mate_f
a Monday Red Win 1 1 -1 -1 -1
a Tuesday Red Lose -1 -1 -1 1 NA
有需要吗?
答案 0 :(得分:2)
如果我们需要每个unique
的“玩家”,请遍历它们并使用spread
转换为“宽”格式
library(tidyverse)
df1 %>%
pull(Player) %>%
unique %>%
map( ~ df1 %>%
select(-Team) %>%
mutate(Player2 = Player, Player = .x) %>%
filter(Player2 != .x) %>%
mutate(Player2 = paste0("Team_mate_", Player2), n = 1) %>%
spread(Player2, n, fill = 0))