我知道我们可以在 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_mean
或custom_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)`.
有人有解决办法吗?最后,用户在调用函数时应该提供的函数是mean
或sum
,而不是custom_mean
或custom_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/