This tutorial shows the standard error options available in leanfe.
All standard error types use YOCO compression from Wong et al. (2021) combined with sparse matrices for blazing fast computation. The sparse matrix approach is used for all SE types (IID, HC1, and clustered) — not just clustered SEs.
YOCO + Sparse Matrix Strategy
When YOCO compression is triggered (low-cardinality FEs, no IV), leanfe:
Compresses data: GROUP BY (regressors + FEs) → sufficient statistics per group
Builds sparse design matrix: FE dummies stored as scipy.sparse (Python) or Matrix::sparseMatrix (R)
Solves sparse WLS: Weighted least squares using sparse matrix operations
Computes SEs: Method varies by vcov type, but all use the sparse design matrix
This applies to all 4 backend/language combinations (Python/Polars, Python/DuckDB, R/Polars, R/DuckDB).
Noteleanfe’s Contribution: Sparse Matrices
The original YOCO paper by Wong et al. (2021) describes the compression strategy and mathematical framework, but focuses on the statistical methodology without addressing how to efficiently represent FE dummy variables in the design matrix. leanfe extends YOCO with sparse matrices — a natural choice since FE dummies are ~99% zeros. This provides ~100x memory savings and faster matrix operations while producing mathematically identical results. See Benchmark Methodology for the full explanation.
Clustered SEs use the same YOCO + sparse design matrix as IID/HC1, plus an additional **sparse cluster matrix W̃_C** (Section 5.3.1 of Wong et al. 2021) for efficient score aggregation:
Within-cluster compression: cluster ID added to GROUP BY (each compressed record → one cluster)
Sparse design matrix: Same as IID/HC1 — FE dummies as sparse matrix
**Sparse cluster matrix W̃_C**: Indicator matrix (G × C) mapping groups to clusters
Vectorized aggregation: cluster_scores = W̃_Cᵀ @ (X × ẽ⁰) — no loops over clusters!
SE comparison for 'treatment':
IID: 0.0094
HC1: 0.0095
Clustered: 0.0229
Two-way: 0.0229
Technical Notes
When is YOCO + Sparse Matrix Used?
The YOCO compression path with sparse matrices is triggered when:
vcov is “iid”, “HC1”, or “cluster” (all three!)
No IV/2SLS instruments
FE cardinality is below thresholds (max single FE ≤ 10,000, total FE levels ≤ 20,000)
When these conditions are met, all 4 implementations (Python/Polars, Python/DuckDB, R/Polars, R/DuckDB) use the same sparse matrix strategy.
Fallback to FWL Demeaning
If FE cardinality is too high or IV is used, leanfe falls back to iterative FWL demeaning (no sparse matrix). This is faster for high-cardinality FEs where the sparse matrix would be huge.