使用quosure作为by参数连接数据集 [英] join datasets using a quosure as the by argument
问题描述
我正在尝试编写一个自定义函数,该函数将使用quos作为参数将两个数据集连接到left_join()函数的 by = c()部分中。
I am trying to write a custom function that will join two datasets using a quosures as the arguments in the "by = c()" portion of the left_join() function.
这是我当前对函数的尝试,在 by = c(!! left_index = !! right_index))部分失败。 left_join期望将这些参数加引号,并用加引号将!!无效。
Here is my current attempt at the function, which fails at the "by = c(!!left_index = !!right_index))" portion. left_join expects these arguments to be quoted and quoting quosures nullifies the !!.
join_by_quosure <- function(data, left_index, var_to_impute, right_index){
require(dplyr)
left_index <- enquo(left_index)
right_index <- enquo(right_index)
var_to_impute <- enquo(var_to_impute)
left_join(data,
data %>% select(!!right_index, !!var_to_impute),
by = c(!!left_index = !!right_index))
}
我在下面编写了该函数的工作示例:
I have written this working example below of how the function would work:
# join_by_quosure(data = mtcars, left_index = vs, var_to_impute = mpg, right_index = am)
left_join(mtcars,
mtcars %>% select(am, mpg),
by = c("vs" = "am"))
如果任何人都可以在left_join()函数的 by = c()部分中提供有关如何调用quasure的见解,我将非常感激。
If anyone can offer insight about how to call a quosure within the "by = c()" portion of the left_join() function I would be very grateful.
推荐答案
c()
函数不支持Rlang爆炸因此您将不得不采用更传统的方法来构建参数。您可以
The c()
function doesn't support the rlang bangs so you'll have to take a more traditional approach to building your parameter. You can do
join_by_quosure <- function(data, left_index, var_to_impute, right_index){
require(dplyr)
left_index <- enquo(left_index)
right_index <- enquo(right_index)
var_to_impute <- enquo(var_to_impute)
by = set_names(quo_name(right_index), quo_name(left_index))
left_join(data,
data %>% select(!!right_index, !!var_to_impute),
by = by)
}
这篇关于使用quosure作为by参数连接数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!