如何在R函数链式调用中共享列参数,无需显式传递给第二个函数
链式调用R函数时共享列参数的实现
我需要链式调用两个自定义R函数,二者均需对同一列执行操作。希望仅在第一个函数中指定该列参数,第二个函数无需显式接收该参数就能自动访问并使用它。
当前实现及问题
以下是当前的代码,执行后返回的是过滤后的总行数21,不符合预期:
filter_function <- function(.x, .y){ .x %>% dplyr::filter({{ .y }} != 4) } count_function <- function(.x, .y){ .x %>% dplyr::count({{ .y }}) } filter_function(mtcars %>% as_tibble(), cyl) %>% count_function(.)
期望得到的结果是按指定列分组计数的 tibble:
# A tibble: 2 × 2 cyl n <dbl> <int> 1 6 7 2 8 14
解决方案:通过数据框属性传递列信息
可以在第一个函数中将目标列的名称存储为数据框的属性,第二个函数读取该属性来获取列名并执行操作,无需显式传递列参数:
library(dplyr) library(rlang) filter_function <- function(.x, .y){ # 捕获并转换列表达式为字符串 target_col <- as_name(enquo(.y)) .x %>% filter({{ .y }} != 4) %>% # 将列名存入数据框的自定义属性 structure(target_col = target_col) } count_function <- function(.x){ # 从属性中读取目标列名 target_col <- attr(.x, "target_col") .x %>% # 使用.data pronoun安全引用列 count(.data[[target_col]]) } # 调用示例 filter_function(mtcars %>% as_tibble(), cyl) %>% count_function()
原理说明
- 在
filter_function中,用enquo捕获传入的列表达式,再通过as_name转换为列名字符串,存入数据框的target_col属性。 count_function读取数据框的target_col属性,用.data[[target_col]]的方式引用目标列,避免非标准求值的歧义问题。
这样调用后即可得到预期的分组计数结果。
内容的提问来源于stack exchange,提问作者C.Robin
相关产品推荐
相关产品推荐

