Joseph Kreke Joseph Kreke - 23 days ago 8
R Question

In R, pass a vector of functions to a another function and refer to each passed function by name

I would like to send a group of functions (a list or a vector) to another function and then within that other function I would like to obtain the names of those individual functions I sent. I also want to use those functions but that seems to be working ok.

For instance:

funcA <- function(x,y){z=x+y}
funcB <- function(x,y){z=x-y}

myfunc <- function(x,y,funclist=c(funcA, funcB)){
func1 <- deparse(substitute(funclist[1]))
}


What I would like func1 to equal is "funcA" but in this example it equals "funclist[1]". If I replace the list with a single function name, such as

myfunc <- function(x,y,funclist=funcA){
func1 <- deparse(substitute(funclist))
}


then I get func1 equals "funcA". I think my shortcoming is in the understanding of deparse(substitute()) but I'm wondering if there's another method I'm overlooking.

Answer
funcA <- function(x,y){z=x+y}
funcB <- function(x,y){z=x-y}

myfunc <- function(x,y,funclist=c(funcA, funcB)){
  func.vec <- as.character(substitute(funclist))
  func1 <- func.vec[2]
  print(func1)
  func2 <- func.vec[3]
  print(func2)
}

myfunc(1,2, c(funcA,funcB))
[1] "funcA"
[1] "funcB"
Comments