首页 > 解决方案 > 使用不同的列名合并两个数据集:left_Join

问题描述

我正在尝试使用两个单独的列名合并两个数据集,但它们共享相同的唯一值。例如,数据集 1 中的列 A == xyzw,而在数据集 2 中,列的名称是 B,但值 == xyzw。

但是,问题在于,在数据集 2 中,列的 B 值 == xyzw 指的是公司名称并出现多次,具体取决于数据集中存在的该公司的员工人数。

本质上,我想创建一个新列,让我们在数据集 1 中将其称为 C,告诉我每个公司有多少员工。

我尝试了以下方法:

## Counting how many teachers are in each matched school, using the "Matched" column from matching_file_V4, along with the school_name column from the sample11 dataset:
merged_dataset <- left_join(sample11,matched_datasets,by="school_name")

虽然此代码有效,但它并没有真正为我提供每家公司的员工人数。

标签: rdplyrleft-jointidyverse

解决方案


如果您可以提供示例数据和预期的输出,它会使其他人更容易提供帮助。但尽管如此,我希望这能给你你想要的:

假设我们有这两个数据框:

df_1 <- data.frame(
  A = letters[1:5],
  B = c('empl_1','empl_2','empl_3','empl_4','empl_5')
)

df_2 <- data.frame(
  C = sample(rep(c('empl_1','empl_2','empl_3','empl_4','empl_5'), 15), 50),
  D = sample(letters[1:5], 50, replace=T)
)


# I suggest you find the number of employees for each firm in the second data frame  


df_2%>%group_by(C)%>%
  summarise(
    num_empl = n()
  )%>%  ### Then do the left join
  left_join(
    df_1,., by=c('B' = 'C') ## this is how you can join on two different column names
  )

#   A      B num_empl
# 1 a empl_1        8
# 2 b empl_2       11
# 3 c empl_3       10
# 4 d empl_4       10
# 5 e empl_5       11

推荐阅读