r - 使用不同的列名合并两个数据集: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")
虽然此代码有效,但它并没有真正为我提供每家公司的员工人数。
解决方案
如果您可以提供示例数据和预期的输出,它会使其他人更容易提供帮助。但尽管如此,我希望这能给你你想要的:
假设我们有这两个数据框:
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
推荐阅读
- python - Python套接字错误10054,连接被远程主机中断
- mysql - 查找过去 6 个月内有活动的用户
- laravel - Laravel 动态复选框错误:试图获取非对象的属性“id”
- python - 在幻灯片烧瓶中显示的磁环
- javascript - 在 Typescript 中,如何定义一个不带参数且不执行任何操作的 void 函数?
- powershell - Powershell - 如何查找指定类型的所有文件及其旁边的文件夹
- javascript - 打字稿真的向后兼容吗?
- perl - Catalyst/Moose:使日志对象始终对外部模块可用
- wpf - 如何使用 MVVM 解决 WPF 中的简单注入器错误“在活动(异步作用域)范围的上下文之外请求实例”?
- python - Python/Tkinter - 新窗口命令