如何在R函数中动态传入left_join的by参数所需的带引号变量名
问题原因
{{ }}(双大括号插值语法)是rlang包提供的、专门用于dplyr/tidyverse函数非标准求值的语法,仅在直接传入tidyverse动词的参数时生效。你将它包裹在引号内后,程序会把"{{variable}}"识别为普通文本字符串,而非你传入的变量名,因此left_join会尝试匹配不存在的{{variable}}列,触发报错。
解决方法
方法1:将传入的变量转为字符串(兼容所有dplyr版本)
使用rlang::enquo()捕获传入的变量表达式,再用rlang::as_name()将其转为字符串格式的列名,直接传给by参数即可:
library(dplyr) dataset_custom <- function(top, dataset, variable) { # 捕获变量并转为字符串列名 var_name <- rlang::as_name(rlang::enquo(variable)) {{dataset}} %>% count({{variable}}) %>% top_n(top, n) %>% arrange(-n) %>% left_join({{dataset}}, by = var_name) }
方法2:使用join_by()语法(仅支持dplyr 1.1.0及以上版本)
dplyr 1.1.0版本推出了更易用的join_by()连接字段定义语法,直接支持双大括号插值,不需要手动转字符串:
library(dplyr) dataset_custom <- function(top, dataset, variable) { {{dataset}} %>% count({{variable}}) %>% top_n(top, n) %>% arrange(-n) %>% left_join({{dataset}}, by = join_by({{variable}})) }
内容的提问来源于stack exchange,提问作者BoyAcc
相关产品推荐
相关产品推荐

