我有两个数据框,想要使用dplyr进行合并。其中一个数据框包含名字。
test_data <- data.frame(first_name = c("john", "bill", "madison", "abby", "zzz"),
stringsAsFactors = FALSE)
另一个数据框包含经过清理的Kantrowitz姓名语料库,标识性别。以下是一个最简示例:
kantrowitz <- structure(list(name = c("john", "bill", "madison", "abby", "thomas"), gender = c("M", "either", "M", "either", "M")), .Names = c("name", "gender"), row.names = c(NA, 5L), class = c("tbl_df", "tbl", "data.frame"))
我基本上想要在 test_data
表格中使用 kantrowitz
表格查找名称的性别。因为我将把这个过程抽象成一个名为 encode_gender
的函数,所以我不知道数据集中将要使用的列的名称,并且不能保证它会像 kantrowitz$name
中一样是 name
。
在基础 R 中,我会按照以下方式执行合并操作:
merge(test_data, kantrowitz, by.x = "first_names", by.y = "name", all.x = TRUE)
这会返回正确的输出:
first_name gender
1 abby either
2 bill either
3 john M
4 madison M
5 zzz <NA>
但是我希望在dplyr中完成这个任务,因为我正在使用该软件包进行所有其他数据操作。 dplyr的by
选项对于各种*_join
函数只允许我指定一个列名,但我需要指定两个。 我正在寻找类似于以下内容的东西:
library(dplyr)
# either
left_join(test_data, kantrowitz, by.x = "first_name", by.y = "name")
# or
left_join(test_data, kantrowitz, by = c("first_name", "name"))
如何使用dplyr执行这种类型的连接?
(不要在意Kantrowitz语料库是识别性别的不好方式。我正在开发更好的实现方法,但我想先使这个工作起来。)