使用ID和匹配的字符串合并两个数据帧

时间:2018-10-20 00:54:05

标签: r if-statement merge stringr grepl

假设我有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"))

dfFinal

此外,在没有匹配项的情况下,homeOdd和awayOdd将为“ NA”

1 个答案:

答案 0 :(得分:0)

我们可以将gather / spreadleft_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是因为df1df2中的名称不同(Vancouver Whitecaps FcVancouver Whitecaps)。