有没有为什么把函数放在r中的函数参数中?

时间:2018-03-12 00:40:38

标签: r function arguments

让我说我有这个功能

 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

1 个答案:

答案 0 :(得分:1)

使用如下名称传递函数:

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