Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 342
Joseph Kreke Avatar asked Nov 22 '25 10:11

Joseph Kreke


1 Answers

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"
like image 64
joel.wilson Avatar answered Nov 24 '25 01:11

joel.wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!