假设我有这个函数
library(dplyr)
x<-c(1,2,3,4,5)
my_function <- function(){
results <- x %>%
sum()%>%
sqrt()
return(results)
}
my_function()
[1] 3.872983
有没有办法在 r 中放置我需要应用的函数在参数中,所以我的代码将是这样的:
my_function <- function(my_first_code,my_second_code){
results <- x %>%
my_first_code()%>%
my_second_code()
return(results)
}
my_function(max,sqrt)
[1] 2.236068
使用函数的名称传递函数,如下所示:
my_function <- function(x, fun1, fun2) {
x %>%
fun1 %>%
fun2
}
my_function(1:5, sum, sqrt)
## [1] 3.872983
通常这样做,允许传递函数或命名它的字符串。
my_function <- function(x, fun1, fun2) {
fun1 <- match.fun(fun1)
fun2 <- match.fun(fun2)
x %>%
fun1 %>%
fun2
}
my_function(1:5, sum, sqrt)
## [1] 3.872983
my_function(1:5, "sum", "sqrt")
## [1] 3.872983