6

Is there a way to determine if the text of two different functions is identical?

x <- function(x) print(x + 2)
y <- function(x) print(x + 2)
identical(x, y)
[1] FALSE
identical(mget("x"), mget("y"))
[1] FALSE
identical(unname(mget("x")), unname(mget("y")))
[1] FALSE
Kevin Burnham
  • 553
  • 2
  • 13

2 Answers2

11

I think this is a good method. It works for many different objects:

all.equal(x,y)
[1] TRUE
Pierre L
  • 28,203
  • 6
  • 47
  • 69
  • 2
    ... and will also show the differences, should there be any – Rich Scriven Sep 16 '16 at 19:07
  • 2
    It's worth noting that `identical` provides more flexible control when comparing functions than the "deparse and compare" of `all.equal`. In R-devel, the "ignore.srcref" argument is added which -when set to TRUE- returns TRUE for `identical(x, y)`. This can be, also, achieved by removing attributes of "x" and "y" -- `identical("attributes<-"(x, NULL), "attributes<-"(y, NULL))`. `?identical` gives an example on the flexibility on bytecompiled functions too; `identical(x, compiler::cmpfun(x))` VS `identical(x, compiler::cmpfun(x), ignore.bytecode = FALSE)` VS `all.equal(x, compiler::cmpfun(x))` – alexis_laz Sep 16 '16 at 20:21
3

Using diffobj package:

library(diffobj)

x <- function(x) print(x + 2)
y <- function(x) print(x + 2)

diffPrint(target = x, current = y)

enter image description here

Wrapping it in any() will give TRUE/FALSE:

any(diffPrint(target = x, current = y))
# FALSE
zx8754
  • 52,746
  • 12
  • 114
  • 209