dplyr`left_join()`不适用于字符对象作为LHS变量 [英] dplyr `left_join()` does not work with a character objects as the LHS variable
问题描述
我可以使用dplyr::left_join(..., by = c("name1" = "name2")
联接包含两个具有不同名称的变量的两个数据集.
I can join two datasets that contain two variables with different names using dplyr::left_join(..., by = c("name1" = "name2")
.
我想使用角色对象left_join(..., by = c(nameOb1 = nameOb2)
加入.奇怪的是:这适用于by = c("name1", nameOb2)
,,但不适用于 by = c(nameOb1, "name2")
.
I want to join using character objects, left_join(..., by = c(nameOb1 = nameOb2)
. Oddly: this works for by = c("name1", nameOb2)
, but not for by = c(nameOb1, "name2")
.
这是为什么?
在下面复制我的问题.非常感谢.
Replication of my issue below. Many thanks.
orig <- tibble(name1 = c("a", "b", "c"),
n = c(10, 20, 30))
tojoin <- tibble(name2 = c("a", "b", "c"),
pc = c(.4, .1, .2))
Works:对by
参数使用字符串
Works: using character strings for the by
arguments
left_join(orig, tojoin, by = c("name1" = "name2"))
# A tibble: 3 x 3
name1 n pc
<chr> <dbl> <dbl>
1 a 10 0.4
2 b 20 0.1
3 c 30 0.2
不起作用:使用object作为 first by
参数的字符串
Does not work: using object as the character string for the first by
argument
firstname <- "name1"
left_join(orig, tojoin, by = c(firstname = "name2"))
# Error: `by` can't contain join column `firstname` which is missing from LHS
# Call `rlang::last_error()` to see a backtrace
Works:使用对象作为 second by
参数的字符串
Works: using object as the character string for the second by
argument
secondname <- "name2"
left_join(orig, tojoin, by = c("name1" = secondname))
# A tibble: 3 x 3
name1 n pc
<chr> <dbl> <dbl>
1 a 10 0.4
2 b 20 0.1
3 c 30 0.2
包装:
dplyr 0.8.0.1
dplyr 0.8.0.1
推荐答案
'left_join'函数需要在by参数中使用命名的字符向量.第二次尝试:
Hy, the 'left_join' function needs a named character vector in the by argument. In your second try:
firstname <- "name1"
left_join(orig, tojoin, by = c(firstname = "name2"))
您将字符向量的名称设置为firstname
,该名称不适用于联接.
为了解决这个问题,您可以先生成一个命名的字符向量,然后将其传递给join函数的by参数
You set the name of the character vector to firstname
which does not work for the join.
For solving this you can first generate a named character vector and pass it then to the by argument of the join function
firstname <- "name1"
join_cols = c("name2")
names(join_cols) <- firstname
dplyr::left_join(orig, tojoin, by = join_cols)
这篇关于dplyr`left_join()`不适用于字符对象作为LHS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!