0

I have a function that accepts a function as an argument. However within my function I need to create a variable depending on which function I passed into it. How can this be achieved?

The following code illustrates the idea (it doesn't work because FUN cannot be compared against mean).

myfunc <- function(x,FUN){
  if(FUN==mean){y <- 1;}else{y <- 2;}
  return(FUN(x+y));
}

Thanks!

David
  • 143
  • 9

1 Answers1

0

Your question is equivalent to "How do I compare functions?". See here, the answer is

myfunc <- function(x, FUN){
  if (identical(FUN, mean)) y <- 1 else y <- 2
  return (FUN(x+y));
}

myfunc(1, mean)
[1] 2 # = mean(1+1)
myfunc(1, sqrt)
[1] 1.732051 # = sqrt(1+2)
Community
  • 1
  • 1
tonytonov
  • 25,060
  • 16
  • 82
  • 98