使用 quosure 作为 by 参数连接数据集 [英] join datasets using a quosure as the by argument
问题描述
我正在尝试编写一个自定义函数,该函数将使用 quosures 作为 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 期望引用这些参数,引用 quosures 会使 !! 无效.
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()"部分中调用 quosure 的见解,我将不胜感激.
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屋!