MatchIt R Package

repository·master·Indexed 42 days ago

https://github.com/kosukeimai/matchit

An R package providing a streamlined interface for matching methods to achieve covariate balance in observational studies for causal inference. It supports various methods including nearest neighbor, optimal, full, genetic, exact, coarsened exact (CEM), cardinality, and subclassification matching, along with propensity score estimation and balance assessment tools like Love plots.

Tokens
3.1K
Snippets
12
Records
18
Agent score
54%

What's inside MatchIt

  1. Configure Full Matching constraints

    master

    When using method = "full", you can control the number of controls per treated unit using the following arguments:

    • min.controls: Forces at least this many controls per treated unit in every stratum.
    • max.controls: Caps the number of controls per treated unit.
    • mean.controls: Targets a specific mean number of controls.
    • omit.fraction: Drops units based on a fraction.

    Constraints and Compatibility:

    • mean.controls and omit.fraction cannot be combined.
    • A caliper cannot be used in conjunction with min.controls in full matching.
    • Tightening min.controls or max.controls typically results in the creation of more strata.
    # Example of full matching with constraints
    matchit(formula, method = "full", min.controls = 2, max.controls = 5)
  2. Configure Coarsened Exact Matching (CEM) with k-nearest neighbor (k2k) matching

    master

    When using method = "cem", you can enable k-nearest neighbor matching by setting k2k = TRUE.

    Important Note on Randomness: Setting k2k.method = NULL does not result in random matching. Instead, it sets all distances to zero and matches in the order provided by m.order. To achieve random matching, you must set m.order = "random" in conjunction with k2k.method = NULL.

    Argument Behavior:

    • The arguments k2k.method, m.order, and mpower are silently ignored if k2k = TRUE is not specified. For example, matchit(..., method = "cem", k2k.method = "manhattan") will perform standard CEM without k2k matching.
    • All nine named values for k2k.method produce distinct pairings.
    • minkowski with the default mpower = 2 is equivalent to euclidean matching.
    # Standard CEM (k2k is OFF, arguments ignored)
    matchit(formula, method = "cem")
    
    # CEM with k2k matching (k2k must be TRUE)
    matchit(formula, method = "cem", k2k = TRUE, k2k.method = "manhattan", m.order = "random")
  3. How MatchIt works: Covariate balance and matching

    master

    MatchIt is designed for nonparametric preprocessing in parametric causal inference. Its goal is to reduce confounding and model dependence when estimating treatment effects by achieving covariate balance between treated and control groups.

    Users typically follow this workflow:

    1. Define a formula: Specify the treatment variable and the covariates to balance (e.g., treat ~ age + educ).
    2. Execute matchit(): Choose a matching method (like nearest neighbor) and a distance metric (like Mahalanobis or propensity scores).
    3. Evaluate Balance: Use summary() and plot() to ensure the matched sample's covariates are similar across groups. If balance is poor, different matching methods or specifications should be tried.
  4. Use `method = "cardinality"` for group balancing

    master
    Cardinality matching balances groups against each other. Note that s.weights (sampling weights) are not supported for method = "cardinality" because this method has no fixed target population to generalize to. If you need to use sampling weights with a fixed target, use profile matching instead (e.g., by setting estimand = "ATE" or ratio = NA).
  5. Use `method = "optimal"` for minimizing within-pair distance

    master

    The optimal matching method minimizes the total within-pair distance. To ensure the solution is truly optimal and not a loose approximation, it is recommended to specify a tight tolerance using the tol argument (e.g., tol = 1e-6 or 1e-9), as the default 1e-3 may return a measurably suboptimal solution on some datasets.

    matchit(formula, data, method = "optimal", tol = 1e-6)
  6. Install MatchIt

    master

    You can install the latest stable version of MatchIt from CRAN using install.packages(). If you require the development version (which may include new features or bug fixes), use the pak package to install directly from GitHub.

    Note: Installing the development version requires R to compile C++ code, which may require additional build tools on your system.

    ```r
    # Install stable version from CRAN
    install.packages("MatchIt")
    
    # Install development version from GitHub
    install.packages("pak") # If not yet installed
    pak::pak("ngreifer/MatchIt")
    ```埋
  7. Benchmarking MatchIt C++ performance

    master

    When benchmarking the C++ components of MatchIt, ensure that both the baseline and the test builds are compiled with the same optimization level (ideally -O2).

    Important Pitfalls:

    • pkgbuild::compile_dll() compiles at -O0 by default. Comparing a committed .so (built at -O2 via R CMD INSTALL) against a debug build (-O0) will result in misleading performance regressions (often appearing 30-60% slower).
    • compile_dll() only recompiles changed files. To ensure a clean, consistent comparison, always run pkgbuild::clean_dll() followed by pkgbuild::compile_dll(debug = FALSE) on both the baseline and the new version.
    • If benchmarking from a git worktree, ensure the PKG_DIR environment variable is set correctly to point to the specific commit being compared.
    # Correct benchmarking workflow
    pkgbuild::clean_dll()
    pkgbuild::compile_dll(debug = FALSE)
  8. Inspect and assess matching results

    master

    After running matchit(), you can inspect the results and assess covariate balance using the following methods:

    1. Print the matchit object: Provides a summary of the matching method, distance metric used, number of observations (original vs. matched), target estimand, and covariates.
    2. Use summary(): Provides a detailed balance table for both the original and matched samples. It includes statistics like Means (Treated/Control), Standardized Mean Difference, Variance Ratio, and eCDF. Smaller values in these statistics generally indicate better balance.
    3. Use plot() on the summary: Generates a 'Love plot' to visually display the standardized mean differences before and after matching.

    Example:

    # 1. Inspect matching details
    m.out
    
    # 2. Check covariate balance statistics
    summary(m.out)
    
    # 3. Visualize balance with a Love plot
    plot(summary(m.out))
  9. Fixing the 'order' function resolution bug

    master

    A known issue in previous versions involved Rcpp::Function("order") resolving to a user-defined function named order in the global environment instead of base::order().

    This has been fixed by explicitly binding to the base environment. If you are extending the C++ source or observing behavior related to sorting, note that the package now uses Environment::base_env()["order"] to ensure the correct R function is called.

  10. Use `cutpoints = NA` in CEM for exact matching

    master

    In Coarsened Exact Matching (CEM), providing cutpoints = NA for a variable is functionally equivalent to cutpoints = 0. This causes the variable to not be binned, resulting in exact matching on that specific variable.

    # Exact matching on a variable within CEM by using NA cutpoints
    matchit(formula, method = "cem", k2k = TRUE, cutpoints = NA)
  11. Combine match data using `rbind()`

    master

    You can stack multiple matchdata objects using rbind().

    Key Behaviors:

    • Column Naming: Column names are determined by the position of the columns in the first input object. For example, rbind(a, b) may result in different column names than rbind(b, a) if the columns distance and prop.score are in different positions.
    • Missing Columns: If an input object lacks a specific column (e.g., a CEM dataset lacking a distance column), rbind() will fill that column with NA for those rows to maintain compatibility with other datasets (e.g., propensity score datasets).
    • Subclass Labels: When stacking objects with subclasses, labels accumulate prefixes (e.g., 1_1_1) to preserve uniqueness.
    # Stacking match data objects
    combined_data <- rbind(match_data_1, match_data_2)
  12. Plotting matchit objects

    master

    The plot() function can be used on matchit objects to visualize results.

    Subclass Plotting:

    • If you provide a subclass argument, such as plot(m, subclass = "2"), the function will attempt to index the specific subclass.
    • Note that providing a character string for a numeric index (e.g., subclass = "2") is supported via coercion.

    Non-interactive sessions:

    • In non-interactive environments (like R CMD check or automated scripts), plot() will automatically fall back to the aggregate plot if a specific subclass is not named, avoiding interactive menu hangs.
    # Plotting the aggregate match
    plot(m)
    
    # Plotting a specific subclass
    plot(m, subclass = 2)