[英]Trying to combine/merge two data frames in R, matching values in two columns and returning a third
我正在嘗試在R中組合兩個數據幀,使用我認為相當於Excel的VLOOKUP函數。
在一個數據框中,我有一個曲棍球比賽中發生的事件列表(每個游戲由不同的賽季和“gcode”代表) - 每場比賽有數百行。
我想添加一個列,告訴我團隊是贏還是輸。 我將結果放在不同的數據框中(結果列表,每個游戲一行)。
如何使用“merge()”或類似功能來執行此操作? 我需要在每個數據框中引用“季節”和“gcode”的功能。
這是兩個示例數據框,以及我想要的結果。
事件清單:
season gcode seconds score_dif
1 20072008 20001 145 2
2 20072008 20001 2055 1
3 20072008 20002 691 0
4 20082009 20053 3528 -1
5 20092010 20104 2787 1
6 20092010 20155 1752 1
7 20102011 20206 2929 0
8 20102011 20257 277 3
9 20102011 20308 2733 -2
10 20132014 20359 3890 -4
結果列表:
season gcode result
1 20072008 20001 1
2 20072008 20002 0
3 20072008 20003 1
4 20072008 20004 0
5 20072008 20005 0
6 20072008 20006 0
7 20072008 20007 0
8 20072008 20008 1
9 20072008 20009 0
10 20072008 20010 1
聯合:
season gcode seconds score_dif result
1 20072008 20001 145 2 1
2 20072008 20001 2055 1 1
3 20072008 20002 691 0 0
4 20082009 20053 3528 -1 0
5 20092010 20104 2787 1 1
6 20092010 20155 1752 1 0
7 20102011 20206 2929 0 0
8 20102011 20257 277 3 0
9 20102011 20308 2733 -2 0
10 20132014 20359 3890 -4 1
謝謝!
使用dplyr
包
library(dplyr)
df <- events %>%
left_join(results)
如果它無法正常工作,您可以在兩個data.frames
創建一個新的列join
:
events$join <- paste0(events$season,events$gcode)
results$join <- ...
接着
df <- events %>%
left_join(results, by = "join")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.