[SOLVED] How create an R function that take a FUN as parameter

Issue

To extend the usability of a R function, we need to pass an argument of type function (FUN), Could you please demonstrate how to declare a function parameter inside in another function and how to call it. Like

MyOperation <- function(x, y, FUN){
    int sum <- x+y
    if (!missing(FUN)) sum<-FUN(sum)}
    return sum
}

Res <- MyOperation(x=1, y=2, FUN=function(n){...})

Solution

You don’t declare variables in R. Also you can specify a default value right in the formal argument list. You don’t need to use missing in this situation.

This runs FUN(x + y) or returns x+y if FUN is not specified.

myOp2 <- function(x, y, FUN = identity) FUN(x + y)

myOp2(1, 2)
## [1] 3

myOp2(1, 3, sqrt)
## [1] 2

One enhancement might be to allow the function to be specified either as a function or as a character string:

myOp2a <- function(x, y, FUN = identity) {
    FUN <- match.fun(FUN)
    FUN(x + y)
}

myOp2a(1, 3, "sqrt")
## [1] 2

myOp2a(1, 3, sqrt)
## [1] 2

This sums x and y if FUN is not specified; otherwise, it runs FUN with the arguments x and y.

myOp3 <- function(x, y, FUN = sum) FUN(x, y)

myOp3(1, 2)   
## [1] 3

myOp3(1, 2, min)
## [1] 1

Answered By – G. Grothendieck

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *