2017-08-13 160 views
0

我有一个包含Zip代码和相应城市的数据集。在某些情况下,邮政编码丢失了,所以我想用邮政编码R中的邮政编码替换它。left_join如何真正起作用? (在R; dplyr)

显然'纽约'有多个邮政编码。在我的交易数据集中,同一位居民多次出现,因此他们的城市也是如此。 “纽约”多次出现。

使用dplyr的left_join功能,加入城市的名字,我得到了相应的邮政编码为城市名称“纽约”,像这样:

10001, 
10002, 
10003, 
etc. 

比较这VLOOKUP时,Excel将始终以第一种可能的查询匹配,在这种情况下为10001.

基于这里的逻辑是什么R在每一行中用不同的邮政编码匹配'纽约'?

+1

参见[这](https://stackoverflow.com/questions/38549/what-is-后内部连接和外部连接之间的差异)和[this](http://stat545.com/bit001_dplyr-cheatsheet.html#left_joinsuperheroes-publishers)。 dplyr基本上做了一个左外连接。另请参阅[this](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-leftright)所有不同的软件包和基础R连接 –

回答

3

左连接将始终以左表中的所有条目,并从右侧表中添加的比赛:

enter image description here

我认为下面的图像显示了逻辑清楚,你可以忽略SQL在那里陈述。

如果您左加入doctorsvisits,我们将以左表为起点,并添加右表中的所有匹配项。在这种情况下,具有doctor_id 212的医生在表visits中有两个匹配,因此两个vistis都被添加到结果表中。

enter image description here

Excel中做什么,因此不能左连接。它只是寻找一个参考值而忽略其余部分。

如果要从Excel复制行为,可以先删除访问表,然后删除连接列中的任何重复项。例如:

visits = data.frame(doctor_id=c('a','b','c','a'),time=c(1,2,3,4)) 
visits = visits[!duplicated(visits$doctor_id),] 

,然后使用该表的左连接。希望这可以帮助!

+0

谢谢弗洛里安为您详细的解释! – Trgovec

2

左连接实际上将你的“x”tibble与“y”tibble合并,保留x的所有条目,但只连接y(通过特定变量)与x中匹配的条目。

,你可以在这里看到下面

dataframe "x" 

    rank      title 
    <chr>      <chr> 
1 2,801.      Lines 
2 2,802.    Nocno zivljenje 
3 2,803.     Saber Google 
4 2,804.     Sacred Vow 
5 2,805. Was hat uns bloß so ruiniert 
6 2,806.      Our Time 
7 2,807.      Orecchie 
8 2,808.   Marshrut postroen 
9 2,809.    Shor Se Shuruaat 
10 2,810. Oru Murai Vanthu Paarthaya 


dataframe "y" 

    rank     genre 
1 2,801.     Drama 
2 2,802. Crime, Drama, Mystery 
3 2,803.    Comedy 
4 2,804.     Drama 
5 2,805.    Comedy 
6 2,806.     Drama 

应用left_join

left_join(x,y, by ="rank") 

"  rank      title     genre 
    <chr>      <chr>     <chr> 
1 2,801.      Lines     Drama 
2 2,802.    Nocno zivljenje Crime, Drama, Mystery 
3 2,803.     Saber Google    Comedy 
4 2,804.     Sacred Vow     <NA> 
5 2,805. Was hat uns bloß so ruiniert     <NA> 
6 2,806.      Our Time     <NA> 
7 2,807.      Orecchie     <NA> 
8 2,808.   Marshrut postroen     <NA> 
9 2,809.    Shor Se Shuruaat     <NA> 
10 2,810. Oru Murai Vanthu Paarthaya     <NA>"