假设我有2个数据帧:
df1 <- data.frame(eventId = c("6770583", "6770529"), home = c("Real Salt Lake", "Vancouver Whitecaps Fc"), away = c("New England Revolution", "Sporting Kansas City"))
df2 <- data.frame(eventId = c("6770583", "6770583", "6770529", "6770529"), currentOddType = c("New England Revolution to win 1-0, 2-0 or 2-1", "Real Salt Lake to win 1-0, 2-0 or 2-1", "Sporting Kansas City to win 1-0, 2-0 or 2-1", "Vancouver Whitecaps to win 1-0, 2-0 or 2-1"), currentOdds = c("7", "4", "4.33", "4.5"))
我想使用eventId和组名合并它们,因为在df2中重复了eventId。
所需结果如下:
dfFinal <- data.frame(eventId = c("6770583", "6770529"), home = c("Real Salt Lake", "Vancouver Whitecaps Fc"), away = c("New England Revolution", "Sporting Kansas City"), homeOdd = c("4", "4.5"), awayOdd = c("7", "4.33"))
此外,在没有匹配项的情况下,homeOdd和awayOdd将为“ NA”
答案 0 :(得分:0)
我们可以将gather
/ spread
与left_join
组合使用
df1 %>%
gather(type, team, -eventId) %>%
left_join(
df2 %>%
separate(currentOddType, into = c("team", "type"), sep = "\\s(?=to win)") %>%
select(eventId, team, currentOdds),
by = c("eventId", "team")) %>%
unite(val, team, currentOdds) %>%
spread(type, val) %>%
separate(away, into = c("away", "awayOdd"), sep = "_") %>%
separate(home, into = c("home", "homeOdd"), sep = "_")
# eventId away awayOdd home homeOdd
#1 6770529 Sporting Kansas City 4.33 Vancouver Whitecaps Fc NA
#2 6770583 New England Revolution 7 Real Salt Lake 4
请注意,Vancouver Whitecaps Fc
变成NA
是因为df1
和df2
中的名称不同(Vancouver Whitecaps Fc
与Vancouver Whitecaps
)。