How to compare functions?

2020-01-26 10:59发布

问题:

Is there a way to compare whether two function objects are the same?

m <- mean
m == mean ## don't work

## this seems not to be the correct way:
functionBody(mean)==functionBody(m)

EDIT: Some more details. I have a function with two arguments (a matrix and a user-defined function which is applied columnwise, e.g. mean, median, ...). If the function is mean I want to use colMean instead (to save some running time).

foo <- function(m, fun) {
  #if (fun==mean) {
  #  return(colMeans(m));
  #} else {
    return(apply(m, 2, fun));
  #}
}

回答1:

You can use identical:

identical(m,mean)


回答2:

I use isTRUE(all.equal(function1,function2)), but this suffers from similar drawbacks to the other methods.

Interestingly though, all.equal gives a nice summary of how the two operands differ (try all.equal(function1,function2).



回答3:

You can convert the functions to strings, and compare those strings.

equal_functions <- function(f,g)
  all( 
    capture.output(print(f)) ==
    capture.output(print(g))
  )
equal_functions(function(x) x, function(x) x) # TRUE

But functions that differ for non-essential reasons will be seen as different.

equal_functions(function(x) x, function(u) u) # FALSE
equal_functions(
  function(x) x, 
  function(x) 
    x
) # FALSE


标签: r function