如何最好地比较公式?

how to best compare formulas?

我希望能够比较两个公式。我想知道使用 identical()== 的 advantages/disadvantages/pitfalls 或 deparsed 公式的相等性。

考虑例如

xx <- ~0
environment(xx) <- new.env()

为了清楚起见,我希望公式在语义上等价;我不关心他们的环境。能够进行公式扩展并忽略项的顺序将是一个好处(例如 ~a*b~b+a+a:b 将是等效的),但这太麻烦了。只要 ~a+b(环境 1)和 ~a+b(环境 2)相同,我将接受 ~a+b~b+a 不等价。

我确实想到写一个比较函数,用 emptyenv() 替换两个值的环境,然后使用 identical(),但这看起来很复杂。

是否有优势 cases/reasons 我不应该只在这里使用 ==

identical returns FALSE 我总是尝试 all.equal 时,它就不那么严格了。引用其帮助页面:

all.equal(x, y) is a utility to compare R objects x and y testing ‘near equality’. If they are different, comparison is still made to some extent, and a report of the differences is returned.

xx <- ~0
environment(xx) <- new.env()

all.equal(xx, ~0)
#[1] TRUE

但在 if 语句中不应按原样使用,正确的方法是 isTRUE(all.equal(.))。再次来自文档:

Do not use all.equal directly in if expressions—either use isTRUE(all.equal(....)) or identical if appropriate.

isTRUE(all.equal(xx, ~0))
#[1] TRUE