0

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Caterina, it might also be instructive to see the code for outer (Just type "outer" on the console, w/o parentheses). It shows how to use match.fun to validate your function, and then how to feed the variables to your function in a safe manner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.