我有兩個數據幀,我想要使用dplyr加入。一個是包含名字的數據框。如何在加入dplyr時爲x和y指定列的名稱?
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"))
我基本上想用kantrowitz
表查找姓名的性別從test_data
表。因爲我要把它抽象成函數encode_gender
,所以我不知道數據集中將要使用的列的名稱,所以我不能保證它會是name
,如kantrowitz$name
。
在基地RI將執行合併是這樣的:
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因爲我使用的包我所有的其他數據操作。各種*_join
函數的dplyr by
選項只允許我指定一個列名,但我需要指定兩個。我正在尋找這樣的事情:
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執行這種連接的方式是什麼?
(別介意坎特羅威茨語料庫是一個不錯的方法,以確定性別。我在努力更好地實施,但我希望得到這第一個工作日)。
您目前不能,但它的做名單:https://github.com/hadley/dplyr/issues/177 – hadley