Caterina Buizza
Caterina Buizza

Reputation: 1

R function with function argument

I need to write a function with a function argument, which will slightly modify the function and return the modified function.

what I have so far is

discriminant.functions <- function(priordist1,PC1)
{
  g1 <- PC1*match.fun(priordist1)
  return(g1)
 }

but it doesn't work - i get the following error message when I call the function:

discriminant.functions(function(x1,x2) 36*x1*x2*(1-x1)*(1-x2),0.5)
Error in PC1 * match.fun(priordist1) : 
  non-numeric argument to binary operator

I am not very experienced with R and so I don't know if there are obvious ways to do this, it really seems like it should be very simple. Any help appreciated, thank you very much!

Upvotes: 0

Views: 124

Answers (1)

agstudy
agstudy

Reputation: 121568

match.fun is used to check if the argument is a function, you need to call the function here. Either directly func(...) or using do.call like this:

 ## use ... for extra func arguments
 discriminant.functions <- 
 function(func,PC1,...){
  match.fun(func)   ## check if func s a function
  function(...) PC1* do.call(func,list(...))
}

I test it for * function:

mult2 <- discriminant.functions ("*",2)
mult2(5,4)
[1] 40

Upvotes: 1

Related Questions