FormulaCompiler.jl and Margins.jl: Efficient Marginal Effects in Julia
Eric Feltham
TL;DR
The paper introduces Margins.jl and FormulaCompiler.jl, two Julia packages designed to compute marginal effects with unprecedented scale and efficiency. By separating a high-level statistical interface from a low-level, zero-allocation computation engine based on position-mapped compilation, the approach achieves O(p) per-row evaluation and dramatically reduces memory usage compared to existing tools. The 2×2 framework (Population vs Profile × Effects vs Predictions) clarifies the quantities computed (AME/MEM/MER vs AAP/APM/APR) and enables robust methods, including delta-method standard errors and elasticities, across complex models with interactions and categorical variables. Benchmark results show up to 622× average speedup and 460× memory reduction over R's marginaleffects, with successful execution on datasets containing hundreds of thousands of observations where prior tools fail, marking a practical and scalable marginal effects solution for Julia's statistical ecosystem.
Abstract
Marginal effects analysis is fundamental to interpreting statistical models, yet existing implementations face computational constraints that limit analysis at scale. We introduce two Julia packages that address this gap. Margins.jl provides a clean two-function API organizing analysis around a 2-by-2 framework: evaluation context (population vs profile) by analytical target (effects vs predictions). The package supports interaction analysis through second differences, elasticity measures, categorical mixtures for representative profiles, and robust standard errors. FormulaCompiler.jl provides the computational foundation, transforming statistical formulas into zero-allocation, type-specialized evaluators that enable O(p) per-row computation independent of dataset size. Together, these packages achieve 622x average speedup and 460x memory reduction compared to R's marginaleffects package, with successful computation of average marginal effects and delta-method standard errors on 500,000 observations where R fails due to memory exhaustion, providing the first comprehensive and efficient marginal effects implementation for Julia's statistical ecosystem.
