library(diffobj) old.opt <- options( diffobj.disp.width=80, diffobj.pager="off", diffobj.format="html" )
Most R object comparison functions are good at telling you that
objects are different, but less so at conveying how they are
different. I wrote
diffobj to provide an "aha, that's how they are different" comparison. In this vignette I will compare
all.equal and to
Disclaimer: I picked the examples here to showcase
diffobj capabilities, not
to carry out a fair and balanced comparison of these comparison functions.
Nonetheless, I hope you will find the examples representative of common
situations where comparison of R objects is useful.
I defined four pairs of numeric vectors for us to compare. I purposefully hid the variable definitions to simulate a comparison of unknown objects.
A1 <- 1:10 B1 <- c(1:9, 11) A2 <- 1:20 B2 <- c(20, 1:19) A3 <- 1:20 B3 <- c(20:21, 1:19)
The objects are different... At this point I would normally print both
B1 to try to figure out how that difference came about since the "mean
relative difference" is unhelpful.
testthat::compare does a better job, but I still feel the need to look at
Aha, that's how they are different!
Let's up the difficulty a little bit:
If you look closely you will see that despite a reported 20/20 differences, the
two vectors are actually similar, at least in the part visible part of the
diffPrint it is obvious that
B2 and is the same as
that the last value has been moved to the first position:
testthat::compare throws in the towel as soon as lengths are unequal:
all.equal does the same.
diffPrint is unfazed:
diffPrint also produces useful output for largish vectors:
A4 <- 1:1e4 B4 <- c(1e4 + 1, A4[-c(4:7, 9e3)]) diffPrint(A4, B4)
Do note that the comparison algorithm scales with the square of the number of differences, so very large and different vectors will be slow to process.
R Core and package authors put substantial effort into
diffPrint takes advantage of this. Compare:
all.equal(lm(hp ~ disp, mtcars), lm(hp ~ cyl, mtcars))
diffPrint(lm(hp ~ disp, mtcars), lm(hp ~ cyl, mtcars))
In these examples I limited
all.equal output to five lines for the sake of
brevity. Also, since
testthat::compare reverts to
all.equal output with
more complex objects I omit it from this comparison.
Another candidate comparison function is
compare::compare. I omitted it from
this vignette because it focuses more on similarities than on differences.
For a more thorough exploration of
diffobj methods and their features please see the primary
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.