使用 merge() 函数仅左连接 R 中的选定列 [英] Left join only selected columns in R with the merge() function
问题描述
我正在尝试向左加入 2 个数据框,但我不想加入第二个数据集中的所有变量:
I am trying to LEFT Join 2 data frames but I do not want join all the variables from the second data set:
例如,我有数据集 1 (DF1):
As an example, I have dataset 1 (DF1):
Cl Q Sales Date
A 2 30 01/01/2014
A 3 24 02/01/2014
A 1 10 03/01/2014
B 4 10 01/01/2014
B 1 20 02/01/2014
B 3 30 03/01/2014
我想离开连接数据集 2 (DF2):
And I would like to left join dataset 2 (DF2):
Client LO CON
A 12 CA
B 11 US
C 12 UK
D 10 CA
E 15 AUS
F 91 DD
我可以使用以下代码离开:
I am able to left join with the following code:
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE) :
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE) :
Client Q Sales Date LO CON
A 2 30 01/01/2014 12 CA
A 3 24 02/01/2014 12 CA
A 1 10 03/01/2014 12 CA
B 4 10 01/01/2014 11 US
B 1 20 02/01/2014 11 US
B 3 30 03/01/2014 11 US
但是,它合并了列 LO 和 CON.我只想合并列 LO.
However, it merges both column LO and CON. I would only like to merge the column LO.
Client Q Sales Date LO
A 2 30 01/01/2014 12
A 3 24 02/01/2014 12
A 1 10 03/01/2014 12
B 4 10 01/01/2014 11
B 1 20 02/01/2014 11
B 3 30 03/01/2014 11
推荐答案
您可以通过对传递到合并中的数据进行子集化来实现:
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
或者您可以在当前合并后简单地删除该列:)
Or you can simply delete the column after your current merge :)
这篇关于使用 merge() 函数仅左连接 R 中的选定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!