Package 'dazdiff'

Title: Value-by-Value Comparison of Two Tables
Description: Compares two tables value by value. A candidate table can be checked against a benchmark whose column types are taken as the truth, with the candidate's columns cast to those types first, or two tables can be checked for equality as peers. Rows are aligned on their identity columns, numeric measures are compared within an optional tolerance, and the result is a long 'data.table' with one row per compared value that traces back to the source rows of both inputs.
Authors: Pedro Baltazar [aut, cre, cph]
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0.9000
Built: 2026-12-01 09:56:19 UTC
Source: https://github.com/pedrobtz/dazdiff

Help Index


The type conversions dazdiff will make

Description

In mode = "benchmark", diff_table() casts each column of the candidate to the type it has in the benchmark. These are the conversions it will attempt and the ones it refuses. A conversion that would need a guess – a number read as a flag, a factor's integer codes read as values – is refused rather than made.

Usage

cast_rules(wide = TRUE)

Arguments

wide

If TRUE (the default), a grid of source types by target types, with "yes" for an allowed conversion, "-" for a refused one and "=" where source and target are the same type. If FALSE, one row per pair, with each rule's note.

Details

A cast that drops the fraction of a value (a double to an integer, a timestamp to its calendar day, a Date holding part of a day to its text) is a truncation: it is made when truncate = TRUE, which is the default, and refused otherwise.

Text is parsed strictly: anything that is not a number, a logical literal or a date in date_format is refused, and that includes the text "NA", since a missing value has to arrive as NA. "NaN" and "Inf" are numbers. A double written as text is written in fixed notation, so 100000 becomes "100000", not "1e+05". A timestamp written as text is its local time in its own timezone, which the text does not record, always as "%Y-%m-%d %H:%M:%S" (midnight included), followed by the fraction of a second to the microsecond when it has one, as in "2024-01-01 10:00:00.25". An integer64 column (from bit64) becomes a double when that is exact, an integer within range, or its decimal text.

A logical column becomes a Date only when every value is NA: that is how readers such as read.csv() and data.table::fread() type a column with no values, and the Date column it stands for is then all NA as well.

Value

A data.table.

Examples

cast_rules()
cast_rules(wide = FALSE)

Compare the columns of two tables

Description

The schema view of a comparison: which columns each table has, their types, and how much their values overlap. It reads every column of both tables, including the ones diff_table() would drop, so it is the place to look when a comparison refuses to run.

Usage

compare_columns(x, y)

Arguments

x, y

Tables to compare: data.frames or data.tables.

Details

Column names are normalized first, as diff_table() does: upper case, with every run of other characters replaced by ⁠_⁠, and ⁠_⁠ trimmed from both ends. So amount in x and Amount in y are one column. Two names in one table that normalize to the same thing are an error.

over_pct is the distinct values shared by both sides over the distinct values seen in either, n_common / n_union. 100 means the two columns draw on exactly the same set of values; a value y invents or one it never uses both pull it down.

The overlap is measured only where the two types agree. %in% coerces before matching, so a numeric 1 would count as a match for the string "1" and two columns that are not the same thing would report a full overlap. A column whose type differs gets NA for n_common, n_union and over_pct.

Value

A data.table with one row per column of either side: the normalized name colname, the names as written in each table (name_x, name_y), the two types and whether they match, the two unique counts, and the value overlap (n_common, n_union, over_pct). Rows follow x's column order, then whatever is only in y. A column missing from one side has NA for that side. A list column has NA counts and no overlap.

Examples

x <- data.frame(id = 1:3, amount = c(1, 2, 3))
y <- data.frame(ID = c(1L, 2L, 4L), Amount = c("1", "2", "3"), note = "a")
compare_columns(x, y)

Explain a comparison by its key columns

Description

Which values of the key columns separate the rows that match from the ones that do not. After diff_table() reports differences, the next question is usually where: one region, one load date, one measure. This answers it from the result alone.

Usage

diff_explain(d, column = NULL, among = c("all", "joined"))

Arguments

d

A result of diff_table().

column

NULL (the default) for the overview of every key column, or one column to break down by value: a key column, in either spelling, or "metric".

among

"all" (the default) counts every record; "joined" only those of rows found in both tables.

Details

Called with no column, it returns one row per key column, and per metric when the result has measures. Each distinct value of the column is classed by the records that hold it: same when every one of them matches, differ when none does, mixed otherwise. A column separates the result when no value is mixed: knowing the value tells whether the record matches.

A column that holds a different value on every row (an id) always separates and explains nothing; it is marked identifies and ranked last. The others come first, fewest mixed values first, then fewest values: the shortest explanation leads.

Called with a column, it returns one row per value of that column, with its counts of each status, most differences first: the values to look at.

Value

A data.table. The overview has column, n_values, same_only, differ_only and mixed (the number of values of each class), separates and identifies. The breakdown has the column's values, n, n_same, n_changed, n_only_x, n_only_y and class.

What is counted

For a key column the unit is the row: a row matches only when every one of its measures does, as in diff_report(). With duplicates = "aggregate" the unit is the key. For metric the unit is the value, one per row and measure, so it can say that only one measure changes.

A row found in only one table and a value that changed usually have different causes. among = "joined" counts only the rows found in both tables, so the explanation is of the changed values alone.

Examples

x <- data.frame(
  id = 1:4,
  region = c("north", "south", "east", "west"),
  amount = c(100, 200, 300, 400)
)
y <- data.frame(
  id = c(1:3, 5L),
  region = c("north", "south", "east", "north"),
  amount = c(100, 200.5, 300, 500)
)
d <- diff_table(x, y, by = c("id", "region"))
diff_explain(d)
diff_explain(d, "region")
diff_explain(d, "region", among = "joined")

Report on a comparison, as text

Description

A bounded, readable account of a diff_table() result: which columns were compared, how the rows of the two tables align, and, for each measure that changed, how often it matches and by how much it differs. Printing the report draws it; the numbers are in the returned list.

Usage

diff_report(d, x_name = "x", y_name = "y", sample_k = 5L)

Arguments

d

A result of diff_table().

x_name, y_name

The names the report gives the two tables.

sample_k

The number of keys shown of the rows found in only one table; 0 hides them.

Details

A row counts as changed when any of its measures changed. With duplicates = "aggregate" the units are keys rather than rows.

The counts describe the records passed in. A filtered result, such as d[status != "same"], is reported as if it were the whole comparison, so its match rates are those of the subset; report the full result for table-level figures.

The layout is adapted from the summary of the Python package diffly.

Value

A dazdiff_report: a list holding the counts the report draws, with format() and print() methods. format() takes unicode, whether to draw with box-drawing characters (by default, when the session's encoding is UTF-8), and returns the lines of text.

Examples

x <- data.frame(id = c("a", "b", "c"), value = c(1, 2, 3))
y <- data.frame(id = c("a", "b", "d"), value = c(1, 2.5, 4))
diff_report(diff_table(x, y))

print(diff_report(diff_table(x, y)), unicode = FALSE)

Summarize a comparison by measure

Description

Counts of each status for every measure of a diff_table() result, and, for the usual one-row-per-value shape, how large the differences are.

Usage

diff_summary(d)

Arguments

d

A result of diff_table().

Details

The magnitudes are taken over every value compared on both sides where both source values are finite. They are filtered on the source values, not on diff: two finite values can differ by more than the largest double, and filtering on the difference would drop exactly that value and report the largest difference in the table as 0. rmse is computed with scaling, so squaring cannot overflow either.

Value

A data.table with one row per measure, in the benchmark's column order (a single row when there are no measures): metric, n, n_same, n_changed, n_only_x, n_only_y, and for the "cells" shape max_abs_diff, mean_abs_diff, rmse and max_rel_diff (NA for a measure with no finite pair).

Examples

x <- data.frame(id = 1:3, amount = c(10, 20, 30), rate = c(1, 1, 1))
y <- data.frame(id = 1:3, amount = c(10, 25, 27), rate = c(1, 1, 1))
diff_summary(diff_table(x, y))

Compare two tables value by value

Description

x is the benchmark: in the default mode = "benchmark" it is the source of truth, and y is the table being tested against it. With mode = "equal" the two are peers, and the question is simply whether they are equal. Rows are aligned on their identity columns and every numeric measure is compared, one row per value, each traceable to its source row in both tables.

Usage

diff_table(
  x,
  y,
  mode = c("benchmark", "equal"),
  by = NULL,
  exclude = NULL,
  row_key = c("none", "position", "sorted"),
  measures = "numeric",
  tolerance = 0,
  rel_tol = 0,
  duplicates = c("disambiguate", "aggregate", "error"),
  cast = mode == "benchmark",
  truncate = TRUE,
  nan_is_na = TRUE,
  date_format = "%Y-%m-%d"
)

Arguments

x

The benchmark table (in "equal" mode, simply the first table).

y

The table to compare with it.

mode

"benchmark" (the default) or "equal". See Modes.

by

Identity columns, by name, in either spelling. NULL (the default) uses every column that is not a measure.

exclude

Columns to leave out of the comparison, by name, in either spelling. They are removed from both tables before anything else, in either mode: an excluded column need not be in both tables, is not announced as dropped or ignored, and does not stop mode = "equal" from calling the rest equal. A name in neither table is a warning, not an error, so one list of technical columns can serve many tables; a name that by or measures also names is an error.

row_key

"none" (the default), "position" or "sorted": add a virtual row_number key column. See Well-formed tables.

measures

"numeric" (the default) compares the double columns; "numeric+integer" the integer columns too. Or column names, which must be numeric or integer, or character(0) for none, which compares whole rows.

tolerance

The largest absolute difference still counted as same.

rel_tol

The largest relative difference still counted as same, relative to the larger magnitude of the two values. A value is same when it is within either tolerance.

duplicates

"disambiguate" (the default), "aggregate" or "error". See Duplicate keys.

cast

Whether to cast y to x's types. Defaults to TRUE in benchmark mode; with FALSE the types must already agree. Equal mode never casts.

truncate

Whether a cast may drop a fraction. See Truncation.

nan_is_na

Whether NaN and NA are the same missing value.

date_format

The format text dates are read in when cast to Date. Text must match it exactly, so a string that merely starts with a date is refused rather than read as one.

Value

A data.table keyed by the identity columns (and key_seq, metric when present), with status a factor with levels same, changed, only_x and only_y. The key includes row_number when row_key added it. Its shape is in attr(d, "shape"):

  • "cells", the usual one: one row per row and measure, with key_seq (only when duplicates were numbered), metric, row_id_x, row_id_y (the source rows, NA on the side the row is missing from), value_x, value_y, diff (value_y - value_x), abs_diff (abs(diff)), rel_diff (abs_diff / pmax(abs(value_x), abs(value_y)), 0 when both are 0, NA unless both are finite) and status.

  • "groups", with duplicates = "aggregate": one row per key and measure, with n_rows_x, n_rows_y, n_na_x, n_na_y, value_key_x, value_key_y (the exact multiset of values, as hexadecimal text from the C library: compare them within one session, not with text stored on another platform) and status. Without measures only the row counts are compared.

  • "rows", when there are no measures: one row per row, with key_seq (when present), row_id_x, row_id_y and status, which is never changed.

The attributes mode, tolerance (abs and rel), name_map (each column's name in x and y), dropped (columns of y dropped in benchmark mode), excluded (the columns exclude removed, as named in x or y), ignored (columns not compared) and truncated (the casts that truncated, with the rows of y each one touched) record what was done on the way.

Modes

  • "benchmark": does y match the benchmark x? Columns of y that x does not have are dropped, with a message. A column of x missing from y is an error. Each compared column of y (in by or measures) is cast to the type it has in x (see cast_rules()), so a number stored as text, or a double stored as an integer, still compares. Columns that are not compared are neither cast nor type-checked. A number cast to text is written with the decimals x uses, when every value of x's column uses the same number of them: 2 in y becomes "2.0" to meet x's "2.0", which a message announces. A value of x that equals one of y's as a number but not as text is warned about, since those rows will not align.

  • "equal": are x and y equal? Every column must be in both tables and have the same type in both; nothing is cast. The result is symmetric: swapping x and y swaps only_x with only_y and negates diff.

Column names

Column names are normalized in both tables before anything else: upper case, with every run of characters other than letters and digits replaced by ⁠_⁠, and ⁠_⁠ trimmed from the ends. Letters outside ASCII are kept, so Größe and Grüße stay two columns. So ⁠unit price⁠, Unit.Price and UNIT_PRICE are one column, in either table. Two names in one table that normalize to the same thing are an error to fix before comparing. The result uses the normalized names; attr(d, "name_map") maps them back.

Truncation

In benchmark mode a cast that drops a fraction – a double to an integer, a number or a timestamp to a whole day – is made by default, because the benchmark's types are taken as the truth: storage such as Spark or Delta turns a locally built double into an integer, and the comparison has to follow it. Each truncation is announced in a message and recorded in attr(d, "truncated"): per column, the count, up to three examples, and in the list column rows the row numbers of y that were truncated, which are the row_id_y of the result. A truncated key column can pair rows that differ (1.5 in y becomes 1 and aligns with x's 1), so read the message when it names a key, and find the rows with d[row_id_y %in% attr(d, "truncated")$rows[[1]]]. Set truncate = FALSE to refuse such casts instead.

Measures and identity

The measures are the numeric columns compared value by value; measures picks them by type or by name, always from x. The row identity is by when given, otherwise every column that is not a measure. With by given, a column in neither role is not compared: that is announced in benchmark mode and an error in equal mode, which cannot call two tables equal while ignoring a column. A numeric column that is part of the identity is matched exactly, with no tolerance. So is a Date key, on its exact value: a Date can hold a fraction of a day, and two Dates that print as the same day then do not align.

With no measures at all the question becomes do the two tables have the same rows?, and the result has one row per row (see Value).

Well-formed tables

A table must have at least one key column to be compared; it may have no measures. When every column is a measure there is nothing to align rows on, and diff_table() refuses unless it is given a key: by, fewer measures, or a virtual one with row_key, which adds a row_number key column to both tables:

  • "position" numbers the rows as they come, so row i of x pairs with row i of y, and a different row order shows as differences.

  • "sorted" numbers the rows after sorting both tables by all their compared columns, so row order does not matter. Compared exactly, that pairs the tables as multisets of rows, and cannot pass two tables that hold different rows. It can pair badly instead: one changed value can move its row within the sort, and the rows after it then pair with the wrong partners and show as changes too. With other key columns, rows are sorted and numbered within each of their groups.

Duplicate keys

When the identity does not tell rows apart, duplicates decides:

  • "disambiguate" numbers the rows of each repeated key in arrival order (key_seq) and pairs them by that number, with a warning: the pairing is an assumption. Reordered rows then show as changes, never as matches. Without measures the repeated rows are identical in every compared column, so pairing them assumes nothing and there is no warning.

  • "aggregate" compares the multiset of values of each key and measure instead, exactly (tolerance must be 0).

  • "error" refuses.

Values

A value is same when both are equal, or when both are finite and their difference is within tolerance or within rel_tol relative to the larger of the two: abs_diff <= tolerance or rel_diff <= rel_tol. Both tolerances default to 0, so by default only equal values are the same. Two missing values are the same; with nan_is_na = TRUE NaN and NA are the same missing value, in measures and in key columns alike.

Conditions

Every condition diff_table() signals has a class, so it can be caught or tested for without matching its text, and inherits from dazdiff_error, dazdiff_warning or dazdiff_message. An error means the question cannot be answered; a warning, that the answer may be wrong; a message reports an expected consequence of the settings.

  • dazdiff_error_input: an argument is malformed.

  • dazdiff_error_columns: columns missing, unknown, or not compared in equal mode; names that are empty or collide once normalized.

  • dazdiff_error_types: a column of a type that cannot be compared, or types that differ where nothing is cast.

  • dazdiff_error_cast: a value that cannot be cast to the benchmark's type.

  • dazdiff_error_keys: no key column to align rows on.

  • dazdiff_error_measures: measures names something that cannot be measured, or a column by names too.

  • dazdiff_error_duplicates: repeated keys under duplicates = "error".

  • dazdiff_error_disjoint: no key appears in both tables. Its field disjoint_columns names the key columns that alone share no value, and constant_columns those among them holding one value in each table (a run id, a source tag), which usually belong in exclude.

  • dazdiff_error_dependency: a suggested package is needed but missing.

  • dazdiff_warning_duplicates: repeated keys paired in arrival order.

  • dazdiff_warning_exclude: exclude names a column in neither table.

  • dazdiff_warning_cast_format: a number of y cast to text does not match x's text for the same number ("2.00" against "2").

  • dazdiff_message_dropped_columns, dazdiff_message_ignored_columns, dazdiff_message_no_measures, dazdiff_message_truncation, dazdiff_message_cast_format: columns of y dropped, columns not compared, no measures, values truncated, numbers written as text in x's format.

Examples

benchmark <- data.frame(id = 1:4, amount = c(10, 20, 30, 40))
tested <- data.frame(
  ID = c("1", "2", "3", "5"),
  Amount = c(10, 20.5, 30, 50),
  loaded_at = "2024-01-01"
)
d <- diff_table(benchmark, tested)
d
d[status != "same"]

# Equal mode: no casting, every column in both tables.
diff_table(benchmark, benchmark, mode = "equal")

# Leave a column out of the comparison, in either table.
diff_table(benchmark, tested, exclude = "loaded_at")

# No key at all: align rows by sorting both tables by their values.
diff_table(
  data.frame(a = c(3, 1, 2), b = c(30, 10, 20)),
  data.frame(a = c(1, 2, 3), b = c(10, 25, 30)),
  row_key = "sorted"
)

# No measures: do the tables have the same rows?
diff_table(data.frame(k = c("a", "b")), data.frame(k = c("b", "c", "a")))

Expect a table to match another

Description

A testthat expectation built on diff_table(): it passes when every compared value is same. expected is the benchmark, as in testthat's expect_equal(object, expected), so the comparison is diff_table(expected, object, ...): object is cast to expected's types and its extra columns are dropped. Pass mode = "equal" to compare the two as peers instead.

Usage

expect_table_equal(
  object,
  expected,
  ...,
  rel_tol = sqrt(.Machine$double.eps),
  max_rows = 10L
)

Arguments

object

The table under test.

expected

The benchmark table.

...

Passed to diff_table(): mode, by, measures, tolerance, duplicates and so on.

rel_tol

The largest relative difference still counted as same, as in diff_table(). With duplicates = "aggregate", which compares exactly, it defaults to 0.

max_rows

The most records that differ shown in a failure.

Details

Unlike diff_table(), which is exact by default, the expectation allows a relative difference of sqrt(.Machine$double.eps) (about 1.5e-8), the default of testthat's expect_equal(): a value computed again rarely agrees with its stored copy to the last bit (0.1 + 0.2 is not 0.3), and a test should not fail on that. It is still far below any difference a person would call real. Pass rel_tol = 0 for an exact comparison.

Duplicate keys are an error (dazdiff_error_duplicates), not a failure: pairing rows by arrival order is an assumption, and an assertion should not rest on one, so the test cannot be judged as written. The exception is a comparison with no measures, where the repeated rows are identical in every compared column and pairing them assumes nothing. Pass duplicates = "disambiguate" or "aggregate" to accept duplicates.

Tables that share no key – most often because object came back empty – fail the expectation. diff_table() refuses such a comparison as ill-formed, but under test it is an answer: the two tables differ in every row.

Value

The diff_table() result, invisibly. On failure it is also attached to the failed expectation, as its "diff" attribute. NULL when the tables share no key, since there is no result.

Examples

expected <- data.frame(id = 1:3, amount = c(10, 20, 30))
actual <- data.frame(id = 1:3, amount = c(10, 20, 30 + 1e-9))
expect_table_equal(actual, expected, tolerance = 1e-6)

Do the two tables match?

Description

TRUE when every record of a diff_table() result is same: no value changed and no row is found in only one table. Two empty tables match.

Usage

is_matching(d, tolerance = NULL, rel_tol = NULL)

Arguments

d

A result of diff_table().

tolerance, rel_tol

NULL (the default) keeps the thresholds of the comparison. A number re-judges the values: a value matches when within either. When only one is given, the other is 0.

Details

With tolerance or rel_tol given, the values are judged again at those thresholds instead of the ones diff_table() used, from the abs_diff and rel_diff it stores. That works in both directions, looser or stricter, so one comparison can be asked at several thresholds without being run again. The rule is diff_table()'s: two equal or two missing values always match, and the tolerances apply to finite pairs only. A row found in only one table never matches, whatever the threshold.

Value

TRUE or FALSE.

Examples

x <- data.frame(id = 1:3, amount = c(100, 200, 300))
y <- data.frame(id = 1:3, amount = c(100, 200.5, 300))
d <- diff_table(x, y)
is_matching(d)
is_matching(d, tolerance = 1)
is_matching(d, rel_tol = 0.001)
is_matching(d, rel_tol = 0.01)

Convert a table to the types dazdiff compares

Description

diff_table() compares columns of five types: character, logical, Date, numeric (double) and integer. In mode = "benchmark" the benchmark x must already hold only those; in mode = "equal" both tables must. This converts the columns that are something else, explicitly, so that any lossy conversion is the caller's choice and not a silent default.

Usage

normalize_dt(dt, to = c(factor = "character"), cols = names(dt))

Arguments

dt

A data.frame or data.table.

to

Named character: which supported type ("character", "logical", "Date", "numeric" or "integer") each other type becomes, named by "factor", "POSIXct" or "integer64". The mappings given are added to the default, factor to "character", and replace it only where they name factor themselves. A column whose type is in neither is an error, not a guess.

cols

The columns to consider, by default all of them.

Details

A factor (ordered or not) becomes its labels by default. A timestamp (POSIXct) has no default: c(POSIXct = "Date") keeps the calendar day in the stamp's own zone (the session's zone for a stamp with none, as it prints) and drops the time, so two stamps on the same day become one value; c(POSIXct = "character") keeps the stamp as text, written as its local time in its own zone as "%Y-%m-%d %H:%M:%S" (with the fraction of a second, to the microsecond, when it has one) and without naming the zone, so the same instant held in two zones becomes two different strings: give both tables the same zone first. Name the one you mean in to.

An integer64 column (from bit64) has no default either: c(integer64 = "numeric") is exact below 2^53 and refuses larger values, "integer" refuses values outside the integer range, and "character" keeps every digit.

Value

A data.table. dt is never modified; a copy is made only when there is something to convert, so the result is dt itself when there is not, and callers must treat it as read-only.

Examples

x <- data.frame(
  day = as.POSIXct("2024-01-01 10:00", tz = "UTC"),
  kind = factor("a"),
  amount = 1.5
)
normalize_dt(x, to = c(POSIXct = "Date", factor = "character"))