Phit

Compare Two Data Sets in R: A Practical Guide

– Reading time: 5 min – Exercise How-To

In this article
  1. Why Compare Data Sets in R?
  2. Initial Structural Comparison
  3. Comparing Distributions and Summary Statistics
  4. Formal Statistical Tests
  5. Comparing Data Frames Row by Row
  6. Common Pitfalls and How to Avoid Them
  7. Frequently Asked Questions

To compare two data sets in R, you typically use a combination of structural checks (e.g., str(), dim(), names()), summary statistics (e.g., summary(), colMeans()), and visual comparisons (e.g., side-by-side boxplots, scatter plots). For formal statistical testing, functions like t.test(), wilcox.test(), or chisq.test() help determine if differences are significant. The right approach depends on whether you are comparing structure, distributions, or specific values.

Why Compare Data Sets in R?

Data comparison is a core task in data analysis: you might compare training and test sets, before-and-after measurements, results from two experiments, or data from two sources to check consistency. R provides a rich set of tools for both exploratory and confirmatory comparisons. Whether you need to verify that two data frames have the same columns, check if distributions differ, or test for equality of means, R has functions to do it efficiently.

Initial Structural Comparison

Before any statistical test, compare the basic structure of the two data sets. Use these functions to get a quick overview:

  • dim() or nrow()/ncol() to compare dimensions.
  • names() or colnames() to check variable names.
  • str() to inspect data types and structure.
  • head() and tail() to peek at the first and last rows.
  • summary() for a quick summary of each column.

For a programmatic check, you can use identical() to test if two objects are exactly the same, or all.equal() to check for near-equality with tolerance. For example, identical(df1, df2) returns TRUE only if the data frames are identical in every cell and attribute. all.equal(df1, df2) returns a description of differences or TRUE if they are approximately equal.

Comparing Distributions and Summary Statistics

Once structure is verified, compare the distributions of key variables. Summary statistics give a quick numeric comparison:

  • summary(df1) and summary(df2) side by side.
  • sapply(df1, mean) vs sapply(df2, mean) for numeric columns.
  • table() for categorical variables to compare counts.
  • quantile() to compare percentiles.

Visual comparisons are often more informative. Use boxplot(value ~ group, data = combined) where combined is a stacked data frame with a grouping variable. For scatter plots, plot(df1$x, df1$y) and points(df2$x, df2$y, col = "red") overlay two sets. The ggplot2 package offers geom_density() or geom_boxplot() with faceting for elegant side-by-side views.

Formal Statistical Tests

When you need to determine if observed differences are statistically significant, choose a test based on your data type and question:

  • Comparing means of two numeric groups: t.test(x, y) for independent samples, or t.test(x, y, paired = TRUE) for paired data. Check assumptions: normality (e.g., shapiro.test()) and equal variances (e.g., var.test()). If assumptions fail, consider wilcox.test().
  • Comparing distributions: ks.test(x, y) (Kolmogorov-Smirnov) tests if two samples come from the same distribution.
  • Comparing categorical variables: chisq.test(table) or fisher.test() for small counts.
  • Comparing variances: var.test(x, y) or bartlett.test() for multiple groups.
  • Comparing multiple groups: aov() for ANOVA, or kruskal.test() for non-parametric.

Always check test assumptions and interpret p-values in context. A small p-value suggests evidence against the null hypothesis, but it does not measure effect size. Report confidence intervals (often included in t.test() output) for a fuller picture.

Comparing Data Frames Row by Row

Sometimes you need to find which rows differ between two data frames with the same structure. The dplyr package provides setdiff() to find rows in one but not the other, and intersect() for common rows. For a detailed comparison, anti_join(df1, df2) returns rows in df1 not in df2. The compareDF package offers a dedicated function compare_df() that produces an HTML report of differences. Base R's merge() with all = TRUE can also reveal mismatches when you inspect rows with NA in key columns.

Common Pitfalls and How to Avoid Them

  • Ignoring data types: A column might be numeric in one data set and character in another, causing identical() to fail. Use str() to check.
  • Different row orders: identical() is sensitive to row order. Sort both data frames by a key before comparing, or use all.equal() which also checks order by default (set check.attributes = FALSE if needed).
  • Missing values: NA handling can affect summaries and tests. Use na.rm = TRUE in functions like mean(), or consider is.na() checks.
  • Floating point precision: Direct equality checks on numeric vectors may fail due to precision. Use all.equal() with a tolerance.
  • Overlooking attributes: Data frames may have different factor levels or attributes. all.equal() reports these differences.

Frequently Asked Questions

How do I check if two data frames are identical in R?

Use identical(df1, df2) for an exact check, or all.equal(df1, df2) to allow for small numeric differences. all.equal() returns TRUE or a character vector describing differences.

What is the best way to compare two numeric vectors?

For summary comparison, use summary() and boxplot(). For formal testing, use t.test() if assumptions hold, or wilcox.test() otherwise. ks.test() compares entire distributions.

How can I compare two data sets with different column names?

First, harmonize column names using names(df2) <- names(df1) if the columns correspond. Then proceed with structural and statistical comparisons. Alternatively, use merge() with by.x and by.y to join on key columns.

Why does identical() return FALSE when data frames look the same?

Possible reasons: different row order, different data types (e.g., integer vs numeric), different factor levels, or different attributes. Use str() and all.equal() to diagnose.

Can I compare more than two data sets at once?

Yes. For numeric variables, use boxplot(value ~ group) with a stacked data frame. For formal tests, ANOVA (aov()) or Kruskal-Wallis (kruskal.test()) extend to multiple groups. For pairwise comparisons, consider pairwise.t.test().

How do I compare two data sets for equality of distributions?

Use the Kolmogorov-Smirnov test: ks.test(x, y). It tests the null hypothesis that two samples come from the same distribution. For visual comparison, overlay empirical cumulative distribution functions with plot(ecdf(x)) and lines(ecdf(y), col = "red").