r - 在 dplyr 中使用 {{}} 调用自定义函数

标签 r dplyr

我知道我们可以在 dplyr 中使用 {{}} 进行非标准评估,但我遇到了一个特殊情况,我不知道如何解决这。假设我有两个具有相同前缀的函数,例如:

custom_mean <- function(x) {
  mean(x, na.rm = TRUE)
}

custom_sum <- function(x) {
  sum(x, na.rm = TRUE)
}

我想让用户选择在 mtcars 的列上应用哪个函数(用户也可以选择)。这就是我使用两个独立函数的方式:

library(dplyr)

apply_mean_on_mtcars <- function(colname) {
  mtcars %>% 
    select({{colname}}) %>% 
    summarise(
      "custom_{{colname}}" := custom_mean({{colname}})
    )
}

apply_sum_on_mtcars <- function(colname) {
  mtcars %>% 
    select({{colname}}) %>% 
    summarise(
      "custom_{{colname}}" := custom_sum({{colname}})
    )
}

apply_mean_on_mtcars(drat)
> custom_drat
> 1    3.596563

apply_sum_on_mtcars(drat)
> custom_drat
> 1      115.09

但我想要一个函数apply_on_mtcars(),用户可以在其中选择要应用的列和函数(即custom_meancustom_sum )。我试过了,但没有成功:

apply_on_mtcars <- function(colname, func) {
  mtcars %>% 
    select({{colname}}) %>% 
    summarise(
      "custom_{{colname}}" := "custom_{{func}}"({{colname}})
    )
}

Error: Problem with `summarise()` input `custom_drat`.
x could not find function "custom_{{func}}"
ℹ Input `custom_drat` is ``custom_{{func}}`(drat)`.

有人有解决办法吗?最后,用户在调用函数时应该提供的函数是meansum,而不是custom_meancustom_sum.

最佳答案

我们也可以使用 match.fun

library(stringr)
library(dplyr)
apply_on_mtcars <- function(colname, func) {
  mtcars %>% 
    select({{colname}}) %>% 
    summarise(
      "custom_{{colname}}" := 
         match.fun(str_c("custom_", func))({{colname}})
    )
}


apply_on_mtcars(drat, "mean")
#    custom_drat
#1    3.596563
apply_on_mtcars(drat, "sum")
#    custom_drat
#1      115.09

关于r - 在 dplyr 中使用 {{}} 调用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66615268/

相关文章:

r - 根据列中的序列中断对数据框进行分组?

使用 r 中的 start with 重命名多个列

突出显示的 R Leaflet Map Polygon Labels 标签不正确

python - 什么是 R 函数(如 str()、summary() 和 head())的 Python pandas 等价物?

xml - 如何使用 R(Rcurl/XML 包)从 Yahoo 抓取选项数据?

r - 将矩阵转换为 r 中的数据帧

r - 使用 dplyr 进行汇总并使用平均值和 sd (+/-) 导出表

r - 将多行数据合并成一列

r - 为 R 中具有相同符号的每个连续数字范围分配一个值

r - dplyr 句点字符 "."指的是什么?