Home > Software design >  Pass a function as an another function argument
Pass a function as an another function argument

Time:12-29

I have two functions, as for example:

a <- function(x) return(mean(x))
b <- function(x) return(median(x))

I would like to have another function that passes either a or b as an argument.

The goal is something like this:

oper <- function(f, x) {
  ifelse(f == "a",  a(x), b(x))
}

If for example I was to execute the function:

oper(a, c(3,4,5))

I get the following error message:

Error in f == "a" : 
comparison (1) is possible only for atomic and list types

Disclosure: mean(x) and median(x) are just for example purposes.

CodePudding user response:

Because R has first-class functions, you can simply pass your function and call it directly:

oper2 <- function(f, x) {
  f(x)
}

x <- c(2, 3, 8)

oper2(a, x)
# 4.333333

oper2(b, x)
# 3
  • Related