library(dsFedAteClient)
library(dsFedAte)
library(DSLite)
library(MASS)†These authors contributed equally to this work.
1 Introduction
Causal inference aims at evaluating the effect of a treatment on an outcome in a specified population. In evidence-based medicine, randomized controlled trials (RCTs) are considered the gold standard for this task, providing unconfounded estimates of average treatment effects (ATEs) that drive high-stakes clinical and regulatory decisions (French Health Authority 2024). However, individual trials often suffer from limited sample sizes and restrictive eligibility criteria, limiting their precision and external validity (Rothwell 2005). Combining information across multiple studies mitigates these limitations, making evidence synthesis through meta-analysis the pinnacle of the clinical evidence hierarchy (Barratt et al. 1999; Evans 2003). Meta-analysis can be conducted using either aggregate data (AD) or individual participant data (IPD). While AD meta-analysis is convenient, IPD meta-analysis offers greater statistical flexibility, enabling covariate adjustment, harmonization of outcomes, and rigorous handling of site effects (Riley and Steyerberg 2010; Burke et al. 2017). Unfortunately, pooling IPD in a centralized repository is frequently prohibited by privacy regulations, institutional governance, and logistical barriers, forcing researchers to rely on less informative study-level summaries.
Federated learning (McMahan et al. 2017) offers a decentralized paradigm to bypass these data-sharing bottlenecks. In a federated network, algorithms are trained collaboratively through the exchange of intermediate aggregate quantities, while the underlying individual-level observations remain local. Recently, this paradigm has been extended to federated causal inference (Xiong et al. 2023; Khellaf et al. 2024), enabling the statistical benefits of an IPD meta-analysis without pooling raw data. Under suitable conditions, federated procedures can output causal effect estimates and variances that match or approximate the results obtained from centrally pooled analyses.
Despite the theoretical maturity of federated causal inference, a major barrier to its widespread adoption is the lack of practical software implementations. While there exist deployment platforms for standard federated machine learning tasks (He et al. 2020; Ziller et al. 2021), there is not for its causal inference methods, hindering their diffusion among researchers.
To bridge this gap, we propose a practical deployment of federated causal inference using DataSHIELD (Wolfson et al. 2010; Gaye et al. 2014). DataSHIELD is an established R-based framework engineered to perform privacy-preserving distributed analyses. It allows participating studies to execute local computations and return only disclosure-controlled summary quantities to a central analysis server. In this article, we extend the DataSHIELD ecosystem by introducing methods for the federated estimation of ATEs across multiple RCTs, providing researchers with a secure, deployable tool to conduct covariate-adjusted IPD meta-analyses without ever centralizing participant-level records.
1.1 Contributions.
We introduce two companion R packages, dsFedAte (server-side) and dsFedAteClient (client-side), implementing within DataSHIELD the federated ATE estimator of Khellaf et al. (2024) using decentralized IPD from multiple RCTs. The implementation builds on native DataSHIELD functions and allows individual-level patient data to remain at their respective sites. Unlike the iterative optimization scheme proposed by Khellaf et al. (2024), we introduce a one-shot federated procedure, better suited to DataSHIELD’s dsBase package and more communication-efficient for moderate covariate dimensions. By aggregating local covariance matrices and covariate–outcome cross-products, it estimates the outcome-model parameters in a single communication round and yields the same ATE as the centralized pooled estimator.
We provide two methodological contributions, beyond the implementation. First, we derive the asymptotic variance in the general setting, accounting for heterogeneous covariate distributions and site effects. We express this variance as a sum of locally computable contributions that can be aggregated centrally, enabling federated variance estimation and the construction of confidence intervals. Second, we extend the known results of linear adjustment in a single RCT to the multiple RCTs setting. We also prove the consistency and asymptotic normality of the estimator even when the outcome models are estimated with misspecified linear regressions (Proposition 2).
Finally, our work contributes to a growing movement of theory-backed implementations for federated causal inference. A complementary approach is available in the dsMatching and dsMatchingClient DataSHIELD packages by Gusinow et al. (2026), who operate in a multi-site observational data setting. Under the assumption of homogeneous nuisance functions across sites, they focus on the federated estimation of parametric propensity scores to derive matching-based estimators. In contrast, we operate within a multiple RCT setting with heterogeneous outcome distributions. We focus on federated g-formula estimators, accommodating site effects and guaranteeing robustness to model misspecification.
2 Background and Problem Statement
2.1 Multicenter Causal Inference
We represent each individual by a realization of the random tuple \((H, X, A, Y)\), where \(H \in [K]\) denotes the study/site/center indicator, \(A \in \{0,1\}\) the binary treatment indicator, \(X\) a \(d\)-dimensional vector of pre-treatment covariates, and \(Y\) the observed outcome. Following the potential outcomes framework of (Rubin 1974), we posit the existence of two counterfactual random variables \(Y^0\) and \(Y^1\), representing the outcomes an individual would have experienced under treatment \(0\) or \(1\), respectively. We link these potential outcomes to the observed outcome \(Y\) through the Stable Unit Treatment Value Assumption (SUTVA), which requires that there is no interference between individuals and no hidden versions of treatment.
Assumption 1 (SUTVA). \(Y = AY^1 + (1-A)Y^0\).
To compare two treatments, one typically specifies a contrast function \(\Phi\) and targets \(\Phi(\mathbb{E}[Y^1], \mathbb{E}[Y^0])\). In this work, we focus on the risk difference \(\Phi(x, y) = x - y\), yielding the estimand of interest: \[\tau:=\mathbb{E}[Y^1 - Y^0]. \tag{ATE}\]
In practice, for any given individual, only one of the two potential outcomes \(Y^1\) or \(Y^0\) is ever observed, a fact known as the fundamental problem of causal inference. The goal is nonetheless to estimate \(\tau\) from the observable quantities \((H, X, A, Y)\), which in general requires imposing assumptions on the joint distribution of \((H, X, A, Y^1, Y^0)\). Beyond SUTVA, we adopt the following conditions on the treatment assignment mechanism.
Assumption 2 (RCT within sites). Treatment is randomised within each site: \(A \perp\!\!\!\perp (Y^{0},Y^{1}) \mid H.\)
Assumption 3 (Positivity). For every \(k\in[K]\), \(0<p_k:=\Pr(A=1\mid H=k)<1\).
Denote by \(P_k\) the covariate distribution in study \(k\), and set \(\rho_k = P(H=k)\). Assumptions 1 to 3 together yield the identification formula \[\tau = \sum_k \rho_k\,\mathbb{E}_{P_k}\!\left[\mu_1(X, k) - \mu_0(X, k)\right]. \tag{G-formula}\] where the response function \(\mu_a\), for \(a \in \{0,1\}\), is defined as \[ \mu_a(x, k) := \mathbb{E}[Y \mid H=k,\, X=x,\, A=a]. \tag{1}\]
To estimate \(\tau\) via (G-formula) from the observed data \(\mathcal{D}=(H_i, X_i, A_i, Y_i)_{i=1}^n\), we proceed in two steps: we first fit estimators \(\hat{\mu}_1\) and \(\hat{\mu}_0\) on the data, and then plug them into (G-formula). For each site \(k\), define the local treatment effect estimate \[ \hat{\tau}_k := \frac{1}{n_k}\sum_{i:\, H_i = k} \big[\hat{\mu}_1(X_i, k) - \hat{\mu}_0(X_i, k)\big], \tag{2}\]
where \(n_k := \#\{i : H_i = k\}\). The overall estimator is then the weighted average \[ \hat{\tau} = \sum_k \frac{n_k}{n} \cdot \hat{\tau}_k. \tag{3}\]
Throughout this work, \(\hat{\mu}_1\) and \(\hat{\mu}_0\) are specified as linear models, that is, for \(a\in \lbrace 0,1\rbrace,\) \[\hat{\mu}_a(x,k) = \hat{d}_a^\top k + \hat{\beta}_a^\top x,\] where \[ ( \hat{d}_a,\, \hat{\beta}_a) = \operatorname*{argmin}_{ d,\, \beta} \sum_{i=1}^n \bigl(Y_i - d^\top H_i - \beta^\top X_i\bigr)^2\mathbb{1}_{[A_i=a]}, \tag{4}\]
with \(H\) encoded as a one-hot vector.
2.1.1 Linear Outcome Model
The tutorial examples in Section 4 all rely on a linear outcome model, implying that \(\hat{\mu}_1\) and \(\hat{\mu}_0\) are correctly specified. The function dsFedAteClient::ds.EstimateAte provides two optional logical parameters, study_effects and heterogeneous, which encode assumptions about the outcome model. Setting study_effects to FALSE imposes the constraint \(\mu_a(\cdot,k)=\mu_a(\cdot,l)\) for all \(k,l\in [K]\), while setting heterogeneous to FALSE assumes that the covariate distributions satisfy \(P_k= P_l\) for all \(k,l\in [K]\). Under linearity, the outcome model takes the form \[
Y^a = d_a^\top H+\beta_a^\top X+\varepsilon_a,
\tag{5}\]
where \(H \in \{0, 1\}^K\) is treated as a one-hot encoded vector (by a slight abuse of notation), \(\mathbb{E}[\varepsilon_a|X,H]=0\). The no study effects assumption corresponds to \[ Y^a = c_a+\beta_a^\top X+\varepsilon_a \tag{6}\]
so that to obtain \(\hat{\mu}_1\) and \(\hat{\mu}_0\), \(Y\) is regressed on \(X\) alone.
study_effects to FALSE amounts to removing the dashed arrow from \(H\) to \(Y\), while setting heterogeneous to FALSE corresponds to removing the dotted arrow from \(H\) to \(X\).
Proposition 1 (Variance, proved in Appendix A). Let \(Z = (H^\top, X^\top)^\top\) and \(\theta_a = (d_a^\top, \beta_a^\top)^\top\). Under Model Equation 5, and homoscedastic errors \(\mathbb{V}(\varepsilon_a \mid Z) = \sigma_a^2\), \(\hat{\tau}\) satisfies \(\sqrt{n}(\hat{\tau} - \tau) \xrightarrow{d} \mathcal{N}(0, V)\), with \[ V = \sigma_1^2 \mathbb{E}[Z]^\top M_1^{-1} \mathbb{E}[Z] + \sigma_0^2 \mathbb{E}[Z]^\top M_0^{-1} \mathbb{E}[Z] + \mathbb{V}(Z^\top \Delta), \tag{7}\]
where \(\Delta = \theta_1 - \theta_0\), \(M_a = \mathbb{E}[\mathbb{1}(A=a) ZZ^\top]\). If we further assume no study effects and fit outcome models on \(X'=(1,X^\top)^\top\), we get \[ V = \sigma_1^2 \mathbb{E}[X']^\top \tilde{M}_1^{-1} \mathbb{E}[X'] + \sigma_0^2 \mathbb{E}[X']^\top \tilde{M}_0^{-1} \mathbb{E}[X'] + \mathbb{V}((\beta_1 - \beta_0)^\top X), \tag{8}\]
where \(\tilde{M}_a = \mathbb{E}[\mathbb{1}(A=a) X' {X'}^\top]\). Finally, if the distribution of covariates is homogeneous across studies, \[ V = \frac{\sigma_1^2}{p} + \frac{\sigma_0^2}{1-p} + \mathbb{V}((\beta_1 - \beta_0)^\top X). \tag{9}\]
A notable robustness result (Lin 2013) shows that in an RCT, even when the true relationship between covariates and potential outcomes is nonlinear, fitting separate linear models for \(\hat{\mu}_a\) and using them to impute potential outcomes still yields a consistent—though only asymptotically unbiased—estimate of the average treatment effect \(\tau\). However, this result applies to a single RCT, whereas in our setting the full pooled data is not an RCT—only the data within each study is. This distinction necessitates a generalization of the above result, the proof of which is deferred to the appendix.
Proposition 2 (Asymptotic normality with misspecified linear outcome models, proved in Appendix C). Let the empirical G-formula estimator \(\hat{\tau}\) Equation 3 be constructed using the arm-specific OLS predictions \(\hat{\mu}_a(X, H) = \hat{d}_a^\top H + \hat{\beta}_a^\top X\), where \(H\) is a vector of one-hot encoded site indicators and \((\hat d_a, \hat\beta_a)\) obtained as in Equation 4. Under Assumption 2 and Assumption 3, and \(X\perp\!\!\!\perp A\mid H\), even if the true conditional expectations are non-linear in \(X\), \(\hat{\tau}\) satisfies\[\sqrt{n}(\hat{\tau} - \tau) \xrightarrow{d} \mathcal{N}(0, V^*),\]where \(V^*\) is the asymptotic variance. Furthermore, \(V^*\) is less than or equal to the asymptotic variance of the unadjusted stratified difference-in-means estimator.
Remark. In particular, this result establishes that when the outcome is binary, one may still use a linear regression to estimate \(\hat{\mu}_a\) as a means to estimate \(\tau\). Moreover, the second part of the proposition justifies the sole focus on the G-formula throughout the rest of the article.
Remark. This extends the asymptotic guarantees of Wager (2024) to multi-site settings. While Liu and Yang (2020) derive a similar variance bound in a stratified RCT, they assume a finite population and use a single pooled and fully interacted regression. In contrast, we use a super-population framework and prove that arm-specific G-formula regressions achieve this bound including site indicators, avoiding centering and interactions.
2.2 Federated Learning and the DataSHIELD Architecture
In multicenter settings, collaboration can increase sample size and population diversity, but legal, privacy, competitive, or logistical constraints may prevent centralizing individual-level data.
Federated computing addresses this by keeping raw observations local while exchanging only aggregated information. It includes federated analytics, which enables collaborative data analysis; and federated learning, which trains a global model without centralizing sites’ raw data. Thus, federated learning is a set of statistical and optimization methods for learning shared models under data-sharing constraints.
Federated architectures can be organized around a star-shaped graph, known as client–server architecture, where sites communicate through a central coordinator, or a fully decentralized architecture, such as peer-to-peer learning, where sites communicate directly without a central server. Finally, two main settings related to the number of participating sites \(K\) are distinguished (Kairouz and McMahan 2021). In cross-device settings, a large number of intermittently available devices, such as smartphones, collaborate. In a cross-silo setting, collaboration is performed by a smaller number of stable organizations, such as hospitals, companies, or research centers.
2.2.1 DataSHIELD
DataSHIELD is an open-source platform for privacy-aware federated analysis of sensitive individual-level data, built around the principle of “taking the analysis to the data, not the data to the analyst” (Gaye et al. 2014). It follows a central client–server architecture (see Figure 2): an analyst interacts through a central client, which sends approved commands to servers located at participating institutions, where the data remain stored locally (Wilson et al. 2017). Note that this terminology is reversed in the federated learning literature, where the central coordinating entity is typically called the server and participating institutions are referred to as clients. DataSHIELD was initially developed mainly for federated analytics, with sites returning disclosure-controlled summary statistics, but its ecosystem now also includes statistical tasks such as fitting distributed linear regressions.
Its architecture combines server-side R packages, such as dsBase, installed within each institution’s infrastructure, with client-side packages, such as dsBaseClient, through which the analyst submits approved analysis commands. Each site’s data are typically managed through an Opal repository, which restricts execution to whitelisted functions and returns only disclosure-controlled outputs. Communication between the client and institutional servers is authenticated and encrypted, allowing distributed analyses to be centrally orchestrated while individual-level data remain behind each site’s firewall.
Server-side functions process the data locally and return only non-disclosive summaries — for example, score vectors and information matrices for a generalised linear model — which the client combines to produce the final result. The procedure is mathematically equivalent to analysing all data in a single database, while respecting the federated constraint. The present package accesses DataSHIELD through the package DSI [Marcon (2025a)][,] an abstraction layer that defines a common interface for connecting to DataSHIELD-compliant data repositories regardless of their back-end implementation (e.g. Opal, DSLite).
2.2.2 Disclosure controls.
In DataSHIELD, privacy is understood primarily as a disclosure control. It prevents the execution of functions whose outputs may reveal individual-level information or enable re-identification or inference attacks. It is enforced operationally at the server side through two mechanisms. First, each data server operates at a configurable privacy control level that determines which server-side functions are permitted (DataSHIELD, n.d.). Five levels are defined, ranging from "permissive" (no restrictions) through "avocado" (blocks known subsetting attacks), "banana" (blocks known inference attacks), and "carrot" (blocks both some subsetting and some inference attacks) to "non-permissive" (blocks all known attacks). The default is "banana", which permits the subsetting and GLM operations used by this package. Second, a set of numeric disclosure thresholds — retrieved via dsBase::listDisclosureSettingsDS() — impose additional constraints on every result returned. The two most relevant to this package are:
nfilter.subset: the minimum number of rows a dataset must contain before any result is returned (default: 3).nfilter.glm: the maximum ratio of model parameters to observations; GLMs that exceed this ratio relative to the local arm size are blocked (default: 0.33, requiring at least \({\sim}\,3\) observations per parameter).
Further safeguards, such as suppression of contingency-table cells with low counts and omission of extrema from quantile functions, are built directly into individual server-side functions (Gaye et al. 2014; Wilson et al. 2017).
2.2.3 Local simulation with DSLite.
The DSLite package (Marcon 2025b) emulates a multi-server DataSHIELD deployment on a single machine by running lightweight virtual servers inside the local R session. All examples in this article use DSLite: they are fully self-contained and reproducible without institutional server access. In a real multi-site study the analyst would replace the DSLite login configuration with credentials for the participating institutional servers; the analysis code is otherwise identical.
2.3 Estimation goals and method
We now describe the outputs of the packages. As in Section 2.1, let \(\mathcal{D}=(H_i,X_i,A_i,Y_i)_{i=1}^n\) denote a set of observations and \((Y_i^1,Y_i^0)_{i=1}^n\) the corresponding potential outcomes, all satisfying Assumptions 1 to 3 for every \(i\). For each site \(k\), define the local data set \(\mathcal{D}_k=\lbrace (H,X,A,Y)\in \mathcal{D}: H=k\rbrace\). As in Section 2.2, suppose that the data sets \(\mathcal{D}_k\) are distributed across \(K\) sites and that all statistical analysis must be conducted without pooling individual-level records.
Goal. We aim to compute the following quantities using only functions from dsBaseClient without individual-level observations being sent out of their site:
The estimator \(\hat{\tau}\) of the ATE defined in Equation 3, with \(\hat{\mu}_1\) and \(\hat{\mu}_0\) predicted as linear models;
A variance estimate \(\hat V\) of \(V\) in Equation 7, yielding a 95 % confidence interval \(\hat\tau \pm 1.96 \hat {V}^{1/2}\).
Method. We obtain estimates of \(\tau\) and \(V\) through the following two steps:
The coefficients \((\hat{d}_a, \hat{\beta}_a)\) defining the outcome models \(\hat{\mu}_0\) and \(\hat{\mu}_1\) — that is, the solutions to Equation 4 — are estimated in a federated manner using
ds.glmfrom thedsBaseClientpackage. This function implements a federated variant of the Iteratively Reweighted Least Squares (IRLS) algorithm.The client broadcasts the estimated coefficients \((\hat{d}_a, \hat{\beta}_a)\) to all servers. Each server \(k\) then computes its local treatment effect estimate \(\hat{\tau}_k\) (see Equation 2), together with the aggregate summaries needed for the variance estimation (see Appendix B for further details), and returns these quantities to the client for final aggregation.
Remark. Estimating \(\hat{\mu}_a\) for \(a\in\{0,1\}\) requires solving Equation 4 across sites without pooling individual-level data. Unlike the iterative federated gradient descent approach of Khellaf et al. (2024), we use DataSHIELD’s ds.glm, which implements federated iteratively reweighted least squares (IRLS). For linear models, IRLS converges in a single iteration by aggregating local score vectors and information matrices. These quantities are already computed by ds.glm, providing the analyst with the global Hessian at no additional communication cost and thus facilitating variance estimation. See Appendix D for details and a comparison with federated gradient descent.
We now describe how to estimate \(V\) in Equation 7, Equation 8, Equation 9 using locally computable quantities that can be aggregated centrally. We first consider the general setting with heterogeneous covariate distributions and site effects (Equation 7).
- Variance of the predicted treatment effects, i.e., \(\mathbb{V}(Z^\top \Delta)\). Let \(\mathcal{I}_k=\{i:H_i=k\}\), \(\bar Z_k=n_k^{-1}\sum_{i\in\mathcal I_k}Z_i\) and \[ S_k=\sum_{i\in\mathcal I_k}\left[\hat\Delta^\top(Z_i-\bar Z_k)\right]^2. \tag{10}\]
The variance \(\mathbb{V}(Z^\top\Delta)\) is estimated by \[\widehat{\mathbb{V}(Z^\top\Delta)} =\frac{1}{n-1}\left[\sum_{k=1}^K S_k+\sum_{k=1}^K n_k(\hat\tau_k-\hat\tau)^2\right],\] where \(\hat\tau_k=\hat\Delta^\top\bar Z_k\) and \(\hat\tau=n^{-1}\sum_k n_k\hat\tau_k\). Since these estimates are already available, only the \(S_k\) need to be transmitted.
The vector \(\mathbb E[Z]\) is estimated by \(\bar Z=\frac{1}{n}\sum_{k=1}^K n_k\bar Z_k\) Thus, only site-specific covariate means and sample sizes are required.
Residual variances. For each treatment arm \(a\in\{0,1\}\), we estimate \[\hat\sigma_a^2=\frac{1}{n^{(a)}-(K+d)} \sum_{k=1}^K\sum_{i\in\mathcal I_k} \mathbb{1}(A_i=a)\left(Y_i-\hat\mu_a(X_i,H_i)\right)^2.\] If the residual variances are assumed equal across treatment arms, we instead use \[\hat\sigma^2=\frac{1}{n-2(K+d)} \sum_{a=0}^1\sum_{k=1}^K\sum_{i\in\mathcal I_k} \mathbb{1}(A_i=a)\left(Y_i-\hat\mu_a(X_i,H_i)\right)^2.\] The required residual sums of squares and degrees of freedom are already provided by
ds.glm().Inverse Gram matrices. We estimate \(M_a^{-1}\) by \(\widehat M_a^{-1}=nG_a\), where \[\label{eq} G_a=\left(\sum_{k=1}^K\sum_{i\in\mathcal I_k} Z_iZ_i^\top\mathbb{1}(A_i=a)\right)^{-1}.\] The matrices \(G_a\) are directly available from
ds.glm()without additional communication.
Without site effects (as in Equation 8), the same estimators apply by replacing \(Z_i\) with \(X_i'=(1,X_i^\top)^\top\) and \(K+d\) with \(d+1\). Under homogeneous covariate distributions and without site effects (Equation 9), the inverse Gram matrices and mean covariates are no longer needed for the residual-variance terms. Only the pooled treatment proportion \(p\), estimated as \(\hat p=n^{-1}\sum_{k=1}^K n_k^{(1)}\) is required.
This represents a novel contribution beyond (Khellaf et al. 2024), and its mathematical derivations and implementation in DataSHIELD are detailed in Appendix B.
3 Package Design
The federated computation of the estimator defined in Equation 3 and described in is realized through the DataSHIELD interface using two companion R packages: dsFedAteClient, which runs on the analyst’s machine, and dsFedAte, which is installed on each participating data server. This follows the standard two-package architecture imposed by DataSHIELD: only the server-side package has direct access to individual-level data, while the analyst communicates with the participating servers exclusively through the aggregate interface provided by the DSI package (Marcon 2025a).
dsFedAteClient runs on the analyst’s machine; dsFedAte is installed on each participating data server. Solid arrows are analyst-to-server queries (DataSHIELD aggregate or assign calls); dashed arrows are the aggregate summaries returned to the analyst.
3.1 Client package: dsFedAteClient
To estimate treatment effects from decentralized RCT data, the analyst only needs to call a single function, ds.EstimateAte(), specifying the treatment, outcome, and covariate variables, as well as the assumptions regarding covariate heterogeneity and site effects. Missing data are not currently supported. The function is supported internally by several unexported helpers: .add_study_id, .check_args(), .check_datasources(), .check_glm_validity(), .compute_variance(), .localAte()).
3.1.1 Pipeline Overview
DataSHIELD distinguishes between two types of functions: assign functions, which perform modifications on the server side without returning data to the analyst, and aggregate functions, which return privacy-safe summaries to the analyst. Using dsFedAteClient, the analyst issues a single call to ds.EstimateAte(); internally, this triggers three kinds of DataSHIELD operations against each data server:
one assign call to the server-side function
addStudyIdDS()from thedsFedAtepackage, issued by the client-side function.add_study_id(only whenstudy_effects = TRUE), corresponding to the outcome model defined in Equation 5. Since the regression requires a site indicator \(H\), and each server only has access to its own site’s data, this indicator is implemented locally as \(K-1\) dummy columns, appended—with study 1 as the reference level—to a new server-side data frame.two assign calls to
ds.dataFrameSubset()fromdsBaseClient, splitting the data into two arm-specific server-side data frames used in the subsequent federated linear regressions to compute \(\hat{\mu}_0\) and \(\hat{\mu}_1\).two aggregate calls to
ds.glm()fromdsBaseClient, fitting the federated arm-specific linear models and returning the estimated coefficient vectors \((\hat{d}_0, \hat{\beta}_0)\) and \((\hat{d}_1, \hat{\beta}_1)\) that define \(\hat{\mu}_0\) and \(\hat{\mu}_1\). Whencompute_variance && heterogeneousisTRUE,viewVarCov = TRUEis additionally passed tods.glm(), which also returns estimates of the matrices \(M_a^{-1}\) or \(\tilde{M}^{-1}\) defined in Proposition 1, needed for the variance estimation – see the matrices \(G_a\) defined in Equation 12 in Appendix B for further details.one aggregate call to
localAteDS()from thedsFedAtepackage — issued by the client-side function.localAte()— which broadcasts \((\hat{d}_0, \hat{\beta}_0)\) and \((\hat{d}_1, \hat{\beta}_1)\) to each server and returns the site-specific estimates \(\hat{\tau}_k\) along with aggregated local summaries, from which the analyst assembles the global estimate \(\hat{\tau}\) and its variance \(\hat{V}(\hat{\tau})\).
Both the first assign call and the last of these aggregate calls reach into the server package dsFedAte. The remaining steps are delegated to the reference DataSHIELD packages dsBase and dsBaseClient.
3.1.2 Arguments
The function ds.EstimateAte takes nine arguments. The first five specify the server connections (datasources) and the string identifiers for the data (base_name) and variables of interest: the outcome \(Y\) (outcome_name), the treatment \(A\) (treatment_name), and the covariates \(X\) (covariate_names). The four variable identifiers are required. The datasources argument is optional; if omitted, the function automatically searches for active connections. The remaining four arguments are Boolean options that control variance estimation and outcome modeling assumptions. These are detailed in Table 1.
ds.EstimateAte().
| Argument | Default | Effect |
|---|---|---|
compute_variance |
TRUE |
If TRUE, returns variance and 95% CI. |
heterogeneous |
TRUE |
If TRUE, computes the variance using Equation 7 or Equation 8 according to whether study_effects is TRUE or FALSE, passing viewVarCov = TRUE to ds.glm() and additionally requiring each server to return its column sums. If FALSE, computes the variance using Equation 9 – see Appendix B for further details. |
heteroscedastic_arms |
FALSE |
If TRUE, \(\sigma_1^2\) and \(\sigma_2^0\) are assumed to differ and are estimated separately from the arm-specific residual sums of squares. If FALSE, the residual sums are pooled and combined after appropriate rescaling. – see Appendix B for further details. |
study_effects |
FALSE |
If TRUE, adds \(K-1\) integer study dummies to the design matrix on each server via the server-side function addStudyIdDS(), invoked by the client-side function .add_study_id. |
3.1.3 Return Values
The result is a named list. Its shape depends on compute_variance, and is documented in Table 2. The vectors n_k and ate_k store the local sample sizes and local average treatment effects, respectively.
ds.EstimateAte().
| Element | Type | Present when |
|---|---|---|
ate |
scalar | Always |
n_total |
scalar | Always |
n_k |
vector | Always |
ate_k |
vector | Always |
variance |
scalar | compute_variance = TRUE |
ci_lower |
scalar | compute_variance = TRUE |
ci_upper |
scalar | compute_variance = TRUE |
3.2 Server package: dsFedAte
The server package exports exactly two functions, both invoked by the client (analyst) via internal calls within ds.EstimateAte(): an aggregate function localAteDS(), called via .localAte, and an assign function addStudyIdDS(), called via .add_study_id.
3.2.1 localAteDS().
This is the core component of the server package. It is called once per server, after ds.glm has converged, with the pooled coefficients \((\hat d_a, \hat \beta_a)\) broadcast back to it. The function then:
Computes the local average treatment effect \(\hat{\tau}_k\) as defined in Equation 2.
If
compute_variance = TRUE, also computes the values \(S_k\) defined in Equation 10.If both
compute_variance = TRUEandheterogeneous = TRUE, it also returns the column sums \(\sum_{i}(1, X_i^\top)^\top\) of the augmented design matrix, allowing the client to reconstruct the global covariate mean \(\bar{X}\) required for the variance estimator in Equation 8 (or its study-augmented counterpart required for Equation 7) – for further details on the federated computation of the variance see Appendix B.
The returned object is a list. Table 3 lists its elements and the conditions under which each is present. The key privacy observation is that the function never returns any vector of length \(n_k\): the server output is a scalar or a vector of length \(d+1\). The disclosure risk therefore scales with the covariate dimension rather than with the local sample size.
localAteDS(). The number of returned scalars per site is bounded by \(3 + d + 2\), independently of \(n_k\).
| Element | Description | Returned when |
|---|---|---|
n_k |
Local sample size \(n_k\) | Always |
n_k_1 |
Local treated count \(n_k^{(1)}\) | Always |
tau_k |
Local ATE \(\hat\tau_k\) as in Equation 2 | Always |
s_k |
The values \(S_k\) as in Equation 10. | compute_variance = TRUE |
g_raw_k |
Column sums of \((1, X)\): length \(d+1\) | compute_variance and heterogeneous both TRUE |
3.2.2 addStudyIdDS().
This assign function takes a data frame name, this server’s 1-based study index \(k\), and the total study count \(K\), and appends \(K-1\) integer dummy columns study_id2, …, study_id\(K\) that encode study membership (study 1 is the reference; on server \(k>1\), the \(k\)-th dummy equals \(1\) and the rest are \(0\)). The augmented data frame is returned and stored by the client under a fresh symbol name via DSI::datashield.assign().
Remark. The dummies are integer columns, not R factors. Locally, every server sees only one value of the study identifier — its own — so a factor column would have a single level, and model.frame() inside ds.glm() would fail with “contrasts can be applied only to factors with 2 or more levels”.
3.3 Data Flow Summary
Figure 3 shows a schema of a single call to ds.EstimateAte() in its default configuration (compute_variance = TRUE, heterogeneous = TRUE, study_effects = FALSE). For readability we show only the client and one server.
Two features of the flow are worth emphasising:
Five server calls, independent of \(K\) and \(n\).
ds.EstimateAte()issues two assigns to split each server’s data frame by treatment arm (ds.dataFrameSubset), two aggregates to fit the per-arm federated OLS (ds.glm, whichdsBaseClientimplements as a federated IRLS – see Appendix D), and one aggregate to collect per-site plug-in pseudo-outcome scalars (localAteDS); each top-level call may itself expand into several network round-trips insidedsBaseClientorDSIfor validation and disclosure-risk reporting. The twods.glmfits and the finallocalAteDSare the three aggregates that carry estimator-relevant payloads. Enablingstudy_effects = TRUEadds one per-site assign (addStudyIdDS). The count depends only on this fixed structure, not on \(K\), \(n\), or \(d\).Communication cost scales with \(O(d^2)\), not \(O(n)\). The communication cost is dominated by the \((d+1)\times(d+1)\) the matrices \(G_a\) defined in Equation 12, one per arm, which are transmitted only when
heterogeneous = TRUE, together with \(O(d)\) column sums per site. All remaining quantities are scalars. Crucially, the local sample sizes \(n_k\) influence only numerical precision and have no other impact on bandwidth, so disclosure risk is determined by the covariate dimension \(d\) rather than by the number of observations. In the special cases wherecompute_variance = FALSE, or wherecompute_variance = TRUEandheterogeneous = FALSE, the protocol only requires scalar exchanges.
ds.EstimateAte() with compute_variance = TRUE and heterogeneous = TRUE. There are five top-level DataSHIELD calls: two ds.dataFrameSubset assigns, two ds.glm aggregates (returning coefficients, residual sums as in Equation 13, and the matrices \(G_a\) as defined in Equation 12), and one .localAte aggregate (returning per-site scalars and a length-\((d+1)\) column-sum vector). Individual outcomes and covariate values never leave the servers.
4 Tutorial Examples
This section walks through five worked examples of federated Average Treatment Effect (ATE) estimation using dsFedAteClient. All examples use DSLite to emulate the federated infrastructure locally — no institutional server access is required. In a real deployment, each site must instead run a DataSHIELD-compatible server, typically either Opal (OBiBa 2024) (the reference implementation) or the lightweight Armadillo (Cadman et al. 2025); see DataSHIELD (2024) for installation and operational guidelines.
From the analyst’s perspective, estimating the ATE from decentralised RCT data requires a single function call — ds.EstimateAte(). Its arguments are the connections (datasources), the server-side data-frame name (base_name), the outcome, treatment, and covariate column names (outcome_name, treatment_name, covariate_names), and the model switches heterogeneous, study_effects, and heteroscedastic_arms. The data at each site must share the same data-frame name and column names, and missing values are not supported.
Following the simulation settings of Appendices C.1–C.4 of Khellaf et al. (2025), Section 4.3 through Section 4.6 cover progressively richer settings: homogeneous covariate distributions; DataSHIELD’s privacy controls in action, where treatment imbalance triggers the nfilter.glm disclosure threshold; heterogeneous covariate distributions; and study-level confounding. Each example closes with a 2000-replication coverage check; the three results are collected in Section 4.8, confirming that the variance formulas in Proposition 1 yield confidence intervals with nominal 95% coverage across these settings.
4.2 Helpers
Six helpers — generate_data(), centralised_ate(), centralised_variance(), make_connections(), run_coverage(), and the pair report_ate() / verify_against_centralised() — are used throughout the examples. The first five are described briefly below; all code is folded by default, click Show to expand it.
generate_data()generates \(K\) RCT datasets from the linear potential-outcomes model (Equation 5, or Equation 6 without study effects), covering three options: heterogeneous/homogeneous covariate distributions, presence/absence of study effects (\(d_k\)), and heteroscedastic/homoscedastic arms corresponding to \(\sigma_0 \neq \sigma_1\) and \(\sigma_0 = \sigma_1\).
Show generate_data()
generate_data <- function(K, d, n, p_k,
c_0, c_1, beta_0, beta_1,
mu, Sigma,
d_k = rep(0, K),
sigma_0 = 1.0,
sigma_1 = 1.0,
seed) {
set.seed(seed)
if (length(n) == 1L) n <- rep(n, K)
if (!is.list(mu)) mu <- replicate(K, mu, simplify = FALSE)
if (!is.list(Sigma)) Sigma <- replicate(K, Sigma, simplify = FALSE)
delta_c <- c_1 - c_0
delta_beta <- beta_1 - beta_0
data_list <- vector("list", K)
Y_0_list <- vector("list", K)
Y_1_list <- vector("list", K)
tau_k <- numeric(K)
for (k in seq_len(K)) {
n_k <- n[k]
# covariates
X_k <- mvrnorm(n = n_k, mu = mu[[k]], Sigma = Sigma[[k]])
colnames(X_k) <- paste0("X", seq_len(d))
# treatment
A_k <- rbinom(n = n_k, size = 1, prob = p_k[k])
# potential outcomes
Y_0 <- as.vector(c_0 + d_k[k] + X_k %*% beta_0 + rnorm(n_k, sd = sigma_0))
Y_1 <- as.vector(c_1 + d_k[k] + X_k %*% beta_1 + rnorm(n_k, sd = sigma_1))
# observed outcome
Y_k <- A_k * Y_1 + (1 - A_k) * Y_0
data_list[[k]] <- data.frame(A = A_k, Y = Y_k, X_k)
Y_0_list[[k]] <- Y_0
Y_1_list[[k]] <- Y_1
# site-level ATE
tau_k[k] <- delta_c + sum(mu[[k]] * delta_beta)
}
list(
data = data_list,
true_ate = sum(n * tau_k) / sum(n),
Y_0 = Y_0_list,
Y_1 = Y_1_list
)
}centralised_ate()computes the plug-in G-formula estimator Equation 3 in a centralised fashion, i.e., with access to the full dataset (not partitioned among servers), with the option to include study effects.
Show centralised_ate()
centralised_ate <- function(data_list, outcome_name, treatment_name,
covariate_names, study_effects = FALSE) {
K <- length(data_list)
pooled <- do.call(rbind, data_list)
if (study_effects)
pooled$study_id <- factor(rep(seq_len(K), times = vapply(data_list, nrow, integer(1L))))
rhs <- c(covariate_names, if (study_effects) "study_id")
rhs_formula <- reformulate(rhs)
formula <- reformulate(rhs, response = outcome_name)
is_treated <- pooled[[treatment_name]] == 1
hat_theta1 <- glm(formula, gaussian, pooled[is_treated, ])
hat_theta0 <- glm(formula, gaussian, pooled[!is_treated, ])
X_all <- model.matrix(rhs_formula, data = pooled)
g <- colMeans(X_all)
list(
ate = as.numeric(g %*% (coef(hat_theta1) - coef(hat_theta0))),
hat_theta1 = hat_theta1,
hat_theta0 = hat_theta0,
X_all = X_all,
treatment_vec = pooled[[treatment_name]]
)
}centralised_variance()computes the variance according to Proposition 1 in a centralised fashion, i.e., with access to the full dataset (not partitioned among servers), covering three options: heterogeneous/homogeneous covariate distributions, presence/absence of study effects, and heteroscedastic/homoscedastic arms corresponding to \(\sigma_0 \neq \sigma_1\) and \(\sigma_0 = \sigma_1\).
Show centralised_variance()
centralised_variance <- function(fit,
heterogeneous = TRUE,
heteroscedastic_arms = FALSE) {
hat_theta1 <- fit$hat_theta1
hat_theta0 <- fit$hat_theta0
X_all <- fit$X_all
g <- colMeans(X_all)
n <- nrow(X_all)
delta_theta <- coef(hat_theta1) - coef(hat_theta0)
tau_i <- as.numeric(X_all %*% delta_theta)
V_samp <- sum((tau_i - fit$ate)^2) / (n * (n - 1L))
if (heteroscedastic_arms) {
sigma2_1 <- sigma(hat_theta1)^2
sigma2_0 <- sigma(hat_theta0)^2
} else {
sigma2_1 <- sigma2_0 <- (deviance(hat_theta1) + deviance(hat_theta0)) /
(df.residual(hat_theta1) + df.residual(hat_theta0))
}
if (heterogeneous) {
V_cov_1 <- summary(hat_theta1)$cov.unscaled
V_cov_0 <- summary(hat_theta0)$cov.unscaled
V_param <- as.numeric(g %*% (sigma2_1 * V_cov_1) %*% g) +
as.numeric(g %*% (sigma2_0 * V_cov_0) %*% g)
} else {
p_hat <- mean(fit$treatment_vec == 1)
V_param <- sigma2_1 / (n * p_hat) + sigma2_0 / (n * (1 - p_hat))
}
V_samp + V_param
}make_connections()creates a mock DSLite federation with one in-memory R object per site. The one thing worth flagging:dsFedAtemethods must be registered manually on each mock server, since DSLite only auto-discoversdsBase.
Show make_connections()
make_connections <- function(data_list, privacy_level = "banana",
nfilter_glm = 0.33) {
options(
datashield.privacyControlLevel = privacy_level,
nfilter.glm = nfilter_glm
)
# Silence DSLite's login/registration chatter.
suppressWarnings(suppressMessages({
K <- length(data_list)
# One DSLite server per site: load data, enable dsBase + dsFedAte,
# register the dsFedAte methods, park the server in .GlobalEnv.
for (k in seq_len(K)) {
srv <- DSLite::newDSLiteServer(tables = list(study_data = data_list[[k]]))
srv$config(DSLite::defaultDSConfiguration(include = c("dsBase", "dsFedAte")))
srv$option("nfilter.glm", nfilter_glm)
srv$aggregateMethod("localAteDS", "localAteDS")
srv$assignMethod("addStudyIdDS", "addStudyIdDS")
assign(paste0(".dslite_srv_", k), srv, envir = .GlobalEnv)
}
# Describe the K logins (URLs and credentials in deployment).
builder <- DSI::newDSLoginBuilder()
for (k in seq_len(K))
builder$append(
server = paste0("study", k),
url = paste0(".dslite_srv_", k),
table = "study_data",
driver = "DSLiteDriver"
)
# Log in and name each site's table `base` on the server.
conns <- DSI::datashield.login(logins = builder$build(), assign = FALSE)
DSI::datashield.assign.table(conns = conns, table = "study_data", symbol = "base")
conns
}))
}run_coverage()repeatedly simulates data (viagenerate_data()), fits the centralised estimator, and checks whether the true ATE lies inside the 95% delta-method confidence interval. Returns the empirical coverage overn_repreplications.
Show run_coverage()
run_coverage <- function(n_rep, n_k, p_k, mu, Sigma,
d_k = rep(0, K), sigma_0 = 1, sigma_1 = 1,
heterogeneous = TRUE,
heteroscedastic_arms = FALSE,
study_effects = FALSE) {
covered <- vapply(seq_len(n_rep), function(i) {
sim <- generate_data(
K = K, d = d, n = n_k, p_k = p_k,
c_0 = c_0, c_1 = c_1, beta_0 = beta_0, beta_1 = beta_1,
mu = mu, Sigma = Sigma, d_k = d_k, sigma_0 = sigma_0, sigma_1 = sigma_1,
seed = i
)
fit <- suppressWarnings(
centralised_ate(sim$data, outcome_name, treatment_name, covariate_names,
study_effects = study_effects)
)
variance <- centralised_variance(fit,
heterogeneous = heterogeneous,
heteroscedastic_arms = heteroscedastic_arms)
se <- sqrt(variance)
CI_lower <- fit$ate - 1.96 * se
CI_upper <- fit$ate + 1.96 * se
sim$true_ate >= CI_lower & sim$true_ate <= CI_upper
}, logical(1))
mean(covered)
}Show report_ate() / verify_against_centralised()
report_ate <- function(label, r, true_ate) {
cat(sprintf("%s ATE: %.4f bias: %+.4f SE: %.4f 95%% CI: [%.4f, %.4f]\n",
label, r$ate, r$ate - true_ate, sqrt(r$variance),
r$ci_lower, r$ci_upper))
}
verify_against_centralised <- function(pooled, pooled_variance, federated) {
cat(sprintf("Centralised ATE: %.4f SE: %.4f\n",
pooled$ate, sqrt(pooled_variance)))
cat("ATE equal: ", isTRUE(all.equal(pooled$ate, federated$ate)), "\n")
cat("Var equal: ", isTRUE(all.equal(pooled_variance, federated$variance)), "\n")
}4.3 Example 1 — Homogeneous populations
Five sites with balanced sample sizes (\(n_k = 200\)), sharing the same covariate distribution — that is, \(X \mid H = k \sim \mathcal{N}(\mu_X, \Sigma_X)\) for all \(k \in [K]\) — and no site effects (study_effects = FALSE). Treatment probabilities differ across sites, \(p_k = (0.65, 0.65, 0.65, 0.35, 0.35)\), but remain sufficiently far away from 0 and 1, so the GLM disclosure filter is satisfied. The outcome follows model Equation 6 with homoscedastic arms (heteroscedastic_arms = FALSE), i.e., \(\sigma_0 = \sigma_1 = 1\). Each site is assumed to recruit from the same population (heterogeneous = FALSE); in the DAG of Figure 1, this corresponds to removing both the dashed arc (\(H \to Y\)) and the dotted arc (\(H \to X\)).
This section verifies that the federated estimator exactly matches its centralised counterpart, and similarly for the variances. It then demonstrates that the variance formula in Equation 9 achieves nominal coverage across 2000 fresh replications of this setting.
Generate data.
mu_X <- c(rep(1, d / 2), rep(-1, d / 2))
Sigma_X <- 0.5 * I_d + 0.5 * J
sim_1 <- generate_data(
K = K, d = d, n = 20 * d, p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
c_0 = c_0, c_1 = c_1, beta_0 = beta_0, beta_1 = beta_1,
mu = mu_X, Sigma = Sigma_X,
seed = 123
)Connect and estimate.
conns_1 <- make_connections(sim_1$data)
result_1 <- ds.EstimateAte(
datasources = conns_1,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
heterogeneous = FALSE,
quiet = TRUE
)Results.
report_ate("Federated ", result_1, sim_1$true_ate)
#> Federated ATE: -1.1694 bias: -0.0694 SE: 0.0886 95% CI: [-1.3431, -0.9958]We verify numerical equality with the centralised estimate:
pooled_1 <- centralised_ate(sim_1$data, outcome_name, treatment_name,
covariate_names)
pooled_1_var <- centralised_variance(pooled_1, heterogeneous = FALSE)
verify_against_centralised(pooled_1, pooled_1_var, result_1)
#> Centralised ATE: -1.1694 SE: 0.0886
#> ATE equal: TRUE
#> Var equal: TRUECoverage. We check that the 95% CI achieves nominal coverage over 2000 fresh replications of this setting:
cov_1 <- run_coverage(
n_rep = 2000,
n_k = 20 * d, p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
mu = mu_X, Sigma = Sigma_X,
heterogeneous = FALSE
)
cat(sprintf("Empirical coverage: %.1f%%\n", 100 * cov_1))
#> Empirical coverage: 94.9%4.4 Example 2 — Disclosure thresholds and privacy levels
Same model parameters as Example 1, but with extreme treatment probabilities \(p_k = (0.9, 0.9, 0.9, 0.1, 0.1)\). With \(n_k = 200\) and \(p = 0.1\), the minority arm contains only 20 observations in expectation. This example illustrates two independent DataSHIELD disclosure controls — an insufficiently low disclosure threshold and an "avocado" privacy level — each triggered by a different operator setting, that can prevent estimation entirely.
Generate data.
sim_2 <- generate_data(
K = K, d = d, n = 20 * d, p_k = c(0.9, 0.9, 0.9, 0.1, 0.1),
c_0 = c_0, c_1 = c_1, beta_0 = beta_0, beta_1 = beta_1,
mu = mu_X, Sigma = Sigma_X,
seed = 7
)Guard 1 — GLM disclosure threshold (nfilter.glm = 0.33) — estimation blocked.
ds.EstimateAte subsets data into arm-specific objects via dataFrameSubsetDS2, then fits an arm-specific OLS via glmDS2. The latter enforces \(d + 1 \leq \texttt{nfilter.glm} \times n_{k}^{(a)}\). Each site has \(n_k = 200\) observations and the minority arm is assigned with probability \(p = 0.1\), giving an expected minority arm size of \(20\). With \(d + 1 = 11\) parameters, the default threshold \(0.33\) blocks the call because \(11 > 0.33 \times 20 = 6.6\).
conns_2 <- make_connections(sim_2$data, privacy_level = "banana", nfilter_glm = 0.33)
ds.EstimateAte(
datasources = conns_2,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
heterogeneous = FALSE
)
#>
#>
#> MODEL FITTING TERMINATED AT FIRST ITERATION:
#> Any values of 1 in the following tables denote potential disclosure risks
#> please use the argument <datasources> to include only valid studies.
#> Errors by study are as follows:
#> 00000
#> 0000000000000000000000000000000000000000000000000000000
#> 00000
#> 00000
#> 00011
#> No errorsNo errorsNo errorsSTUDY DATA OR APPLIED MODEL INVALID FOR THIS SOURCESTUDY DATA OR APPLIED MODEL INVALID FOR THIS SOURCE
#>
#>
#> MODEL FITTING TERMINATED AT FIRST ITERATION:
#> Any values of 1 in the following tables denote potential disclosure risks
#> please use the argument <datasources> to include only valid studies.
#> Errors by study are as follows:
#> 00000
#> 0000000000000000000000000000000000000000000000000000000
#> 00000
#> 00000
#> 11100
#> STUDY DATA OR APPLIED MODEL INVALID FOR THIS SOURCESTUDY DATA OR APPLIED MODEL INVALID FOR THIS SOURCESTUDY DATA OR APPLIED MODEL INVALID FOR THIS SOURCENo errorsNo errors
#> Error in `.check_glm_validity()` at FranciscoAndrade90-dsFedAteClient-5d3d720/R/ds.EstimateAte.R:211:3:
#> ✖ DataSHIELD blocked the GLM in 5 study/studies: study4, study5, study1,
#> study2, study3.
#> ℹ At least one treatment subset in those studies has too few observations
#> relative to the 11 model parameters.
#> ℹ DataSHIELD's nfilter.glm threshold requires each arm to have at least
#> n_params / nfilter.glm observations (default: 11 / 0.33 = 34).
#> → Consider reducing the number of covariates, or exclude the affected studies
#> via the `datasources` argument.Guard 1 resolved — raised threshold (nfilter.glm = 0.6) — estimation succeeds.
Raising nfilter.glm to \(0.6 > 11/20 = 0.55\) satisfies the threshold. The estimate comes through with a larger standard error than Example 1 because extreme arm imbalance reduces effective sample size.
conns_2 <- make_connections(sim_2$data, privacy_level = "banana", nfilter_glm = 0.6)
result_2 <- ds.EstimateAte(
datasources = conns_2,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
heterogeneous = FALSE,
quiet = TRUE
)report_ate("Federated ", result_2, sim_2$true_ate)
#> Federated ATE: -1.1582 bias: -0.0582 SE: 0.0919 95% CI: [-1.3384, -0.9780]Guard 2 — Privacy level "avocado" — subsetting blocked.
The "avocado" level blocks known subsetting attacks, so dataFrameSubsetDS2 is not permitted under it. Because subsetting occurs before (see Figure 3) both the GLM and the localAteDS stages, the error originates from dataFrameSubsetDS2. Raising nfilter.glm does not help since the GLM stage is never reached.
conns_2 <- make_connections(sim_2$data, privacy_level = "avocado", nfilter_glm = 0.6)
ds.EstimateAte(
datasources = conns_2,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
heterogeneous = FALSE
)
#> Error:
#> ! There are some DataSHIELD errors, list them with datashield.errors()Switching back to "banana" with nfilter.glm = 0.6 — as in the block above — restores estimation.
4.5 Example 3 — Heterogeneous covariate distributions
Five sites with unbalanced sample sizes (\(n_1 = 600\), \(n_2 = \ldots = n_5 = 120\)), each recruiting from a distinct patient population: the covariate mean \(\mu_k\) and covariance \(\Sigma_k\) vary across sites, so \(X \mid H = k \sim \mathcal{N}(\mu_k,
\Sigma_k)\). Treatment probabilities are the same as Example 1, \(p_k = (0.65, 0.65, 0.65, 0.35, 0.35)\); even the smallest sites have an expected minority arm size of \(0.35 \times 120 = 42 > 33\), so the default "banana" settings apply. The outcome follows model Equation 6 with no site effects (study_effects = FALSE) and homoscedastic arms (heteroscedastic_arms = FALSE). Each site recruits from a different population (heterogeneous = TRUE); in the DAG of Figure 1, this corresponds to removing the dashed arc (\(H \to Y\)) while keeping the dotted arc (\(H \to X\)).
Under distributional shift the homogeneous variance formula is no longer valid; the formula in Equation 8 must be used instead. Similar to Example 1, this section verifies that the federated estimator matches its centralised counterpart and that the heterogeneous variance formula achieves nominal 95% coverage across 2000 fresh replications.
Define site-specific distributions.
mu_list <- list(
c(rep( 1.0, d / 2), rep(-1.0, d / 2)),
c(rep(-1.0, d / 2), rep( 1.0, d / 2)),
rep(0, d),
c(rep( 0.5, d / 2), rep(-1.0, d / 2)),
c(rep( 1.2, d / 2), rep( 0.8, d / 2))
)
Sigma_1 <- 0.5 * I_d + 0.5 * J
Sigma_list <- list(
Sigma_1,
20 * Sigma_1 + 0.5 * I_d - 0.5 * J,
0.02 * Sigma_1 + 0.7 * I_d,
1.0 * Sigma_1 + 0.5 * I_d - 0.15 * J,
1.5 * Sigma_1 + 0.5 * I_d - 0.15 * J
)Generate data.
sim_3 <- generate_data(
K = K, d = d, n = c(600, 120, 120, 120, 120), p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
c_0 = c_0, c_1 = c_1, beta_0 = beta_0, beta_1 = beta_1,
mu = mu_list, Sigma = Sigma_list,
seed = 123
)Connect and estimate.
conns_3 <- make_connections(sim_3$data)
result_3 <- ds.EstimateAte(
datasources = conns_3,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
heterogeneous = TRUE,
quiet = TRUE
)Results.
report_ate("Federated ", result_3, sim_3$true_ate)
#> Federated ATE: -0.1953 bias: +0.1130 SE: 0.1307 95% CI: [-0.4516, 0.0609]pooled_3 <- centralised_ate(sim_3$data, outcome_name, treatment_name,
covariate_names)
pooled_3_var <- centralised_variance(pooled_3, heterogeneous = TRUE)
verify_against_centralised(pooled_3, pooled_3_var, result_3)
#> Centralised ATE: -0.1953 SE: 0.1307
#> ATE equal: TRUE
#> Var equal: TRUECoverage. We check that the 95% CI achieves nominal coverage over 2000 fresh replications of this setting:
cov_3 <- run_coverage(
n_rep = 2000,
n_k = c(600, 120, 120, 120, 120),
p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
mu = mu_list, Sigma = Sigma_list,
heterogeneous = TRUE
)
cat(sprintf("Empirical coverage: %.1f%%\n", 100 * cov_3))
#> Empirical coverage: 96.6%4.6 Example 4 — Study effects
Five sites with unbalanced sample sizes (\(n_1 = 600\), \(n_2 = \ldots = n_5 = 300\)), using the same site-specific covariate distributions as Example 3. Treatment probabilities are the same as Example 1, \(p_k = (0.65, 0.65, 0.65, 0.35, 0.35)\); the smallest sites have an expected minority arm size of \(0.35 \times 300 = 105 \gg 33\), so the default "banana" settings apply. The outcome follows model Equation 5 with site effects \(d_k = (1, 2, -1, 30, 2)\) (study_effects = TRUE) and heteroscedastic arms \(\sigma_0 = 0.5\), \(\sigma_1 = 3.0\) (heteroscedastic_arms = TRUE). Each site recruits from a different population (heterogeneous = TRUE); in the DAG of Figure 1, both arcs are present: the dashed arc (\(H \to Y\), via \(d_k\)) and the dotted arc (\(H \to X\)).
Because \(d_k\) enters both potential outcomes equally it does not change the true ATE — the shift cancels in \(Y^{(1)} - Y^{(0)}\) — but when a site with a large shift (\(d_4 = 30\)) also has lower treatment probability (\(p_4 = 0.35\)), the unadjusted estimator conflates the site shift with the treatment effect. Augmenting the design matrix with \(K - 1\) site-membership dummies absorbs the shifts (study_effects = TRUE). This section shows the bias of the unadjusted estimator, verifies that the adjusted estimator recovers the true ATE, and confirms nominal 95% coverage across 2000 fresh replications.
Generate data.
sim_4 <- generate_data(
K = K, d = d, n = c(600, 300, 300, 300, 300), p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
c_0 = c_0, c_1 = c_1, beta_0 = beta_0, beta_1 = beta_1,
mu = mu_list, Sigma = Sigma_list,
d_k = c(1, 2, -1, 30, 2),
sigma_0 = 0.5, sigma_1 = 3.0,
seed = 123
)Connect.
conns_4 <- make_connections(sim_4$data)Unadjusted — biased.
With study_effects = FALSE, the design matrix contains only the \(d\) covariates \(X\); the site-intercept shifts \(d_k\) are omitted from the regression. This leads to a biased estimator.
result_4_unadj <- ds.EstimateAte(
datasources = conns_4,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
study_effects = FALSE,
heterogeneous = TRUE,
quiet = TRUE
)cat(sprintf("Unadjusted ATE: %.4f bias: %+.4f (true ATE: %.4f)\n",
result_4_unadj$ate,
result_4_unadj$ate - sim_4$true_ate,
sim_4$true_ate))
#> Unadjusted ATE: -4.3609 bias: -4.4484 (true ATE: 0.0875)Adjusted — unbiased.
result_4_adj <- ds.EstimateAte(
datasources = conns_4,
base_name = "base",
outcome_name = outcome_name,
treatment_name = treatment_name,
covariate_names = covariate_names,
study_effects = TRUE,
heterogeneous = TRUE,
heteroscedastic_arms = TRUE,
quiet = TRUE
)cat(sprintf(
" Adjusted ATE: %.4f bias: %+.4f SE: %.4f 95%% CI: [%.4f, %.4f]\n",
result_4_adj$ate, result_4_adj$ate - sim_4$true_ate,
sqrt(result_4_adj$variance), result_4_adj$ci_lower, result_4_adj$ci_upper
))
#> Adjusted ATE: 0.0556 bias: -0.0319 SE: 0.1472 95% CI: [-0.2329, 0.3441]The adjusted estimate recovers the true ATE and the 95% CI covers it.
Verify equality with centralised adjusted analysis.
pooled_4 <- centralised_ate(sim_4$data, outcome_name, treatment_name,
covariate_names, study_effects = TRUE)
pooled_4_var <- centralised_variance(pooled_4,
heterogeneous = TRUE,
heteroscedastic_arms = TRUE)
verify_against_centralised(pooled_4, pooled_4_var, result_4_adj)
#> Centralised ATE: 0.0556 SE: 0.1472
#> ATE equal: TRUE
#> Var equal: TRUECoverage. We check that the 95% CI achieves nominal coverage over 2000 fresh replications of this setting:
cov_4 <- run_coverage(
n_rep = 2000,
n_k = c(600, 300, 300, 300, 300),
p_k = c(0.65, 0.65, 0.65, 0.35, 0.35),
mu = mu_list, Sigma = Sigma_list,
d_k = c(1, 2, -1, 30, 2), sigma_0 = 0.5, sigma_1 = 3.0,
heterogeneous = TRUE, heteroscedastic_arms = TRUE, study_effects = TRUE
)
cat(sprintf("Empirical coverage: %.1f%%\n", 100 * cov_4))
#> Empirical coverage: 95.5%4.7 Example 5 — Consistency under model misspecification
Examples 1–4 all assumed a linear outcome model, which matched the data-generating process by construction. This final example demonstrates a stronger result: the plug-in G-formula estimator obtained by regressing on \(X\) and \(H\) remains consistent for the ATE even when the true outcome model is nonlinear—the content of Proposition 2.
We retain the covariate and treatment-assignment structure of Example 3 — heterogeneous covariates and treatment probabilities \(p_k = (0.65, 0.65, 0.65, 0.35, 0.35)\) — but now generate a binary outcome via a logistic model, \[\begin{equation} Y^{a} \mid X = x,\, H = k \;\sim\; \mathrm{Bernoulli}\!\bigl(\sigma(c_a + x^\top \beta_a)\bigr), \end{equation}\]
so the linear G-formula is now misspecified. The outcome-model coefficients \((c_a, \beta_a)\) used here are rescaled from the shared parameters so that the linear predictor stays in the sensitive range of the logistic link and the resulting ATE is of practical magnitude:
c_0_ex5 <- 0
c_1_ex5 <- 2
beta_0_ex5 <- 0.5 * beta_0
beta_1_ex5 <- 0.5 * beta_1
p_k_ex5 <- c(0.65, 0.65, 0.65, 0.35, 0.35)Although the data generating process has no site effects, study_effects = TRUE must still be passed to centralised_ate(), or, in a federated setting, to ds.EstimateAte().
True ATE. Computed by Monte Carlo on a very large draw:
# Reference ATE from a large Monte Carlo draw
sim_truth <- generate_data(
K = K, d = d, n = 5000 * c(600, 120, 120, 120, 120),
p_k = p_k_ex5,
c_0 = c_0_ex5, c_1 = c_1_ex5, beta_0 = beta_0_ex5, beta_1 = beta_1_ex5,
mu = mu_list, Sigma = Sigma_list,
sigma_0 = 0, sigma_1 = 0,
seed = 999
)
tau_true <- mean(plogis(unlist(sim_truth$Y_1)) - plogis(unlist(sim_truth$Y_0)))
cat(sprintf("Monte Carlo true ATE: %.5f\n", tau_true))
#> Monte Carlo true ATE: 0.13838Simulation. For each total sample size \(n\), we approximate the MSE by averaging the squared bias over 2000 Monte Carlo replications. Each replication generates a dataset, overwrites each site’s Y with Bernoulli draws from the logistic model, and fits the linear G-formula with study_effects = TRUE:
n_base <- c(600, 120, 120, 120, 120)
n_scale <- c(0.5, 1, 2, 5, 10)
n_tot <- n_scale * sum(n_base)
n_rep <- 2000
# Overwrite each site's Y with Bernoulli draws from the logistic model.
# This is the step that makes the linear G-formula misspecified.
binarize_outcome <- function(sim) {
for (k in seq_along(sim$data)) {
A_k <- sim$data[[k]]$A
eta <- A_k * sim$Y_1[[k]] + (1 - A_k) * sim$Y_0[[k]]
sim$data[[k]]$Y <- rbinom(length(eta), 1, plogis(eta))
}
sim$data
}
# One replication: generate -> binarize -> estimate -> return bias.
simulate_bias <- function(n_vec, seed) {
sim <- generate_data(
K = K, d = d, n = n_vec, p_k = p_k_ex5,
c_0 = c_0_ex5, c_1 = c_1_ex5, beta_0 = beta_0_ex5, beta_1 = beta_1_ex5,
mu = mu_list, Sigma = Sigma_list,
sigma_0 = 0, sigma_1 = 0, seed = seed
)
set.seed(seed + 1e6)
fit <- suppressWarnings(
centralised_ate(binarize_outcome(sim), outcome_name, treatment_name,
covariate_names, study_effects = TRUE)
)
fit$ate - tau_true
}
bias_mat <- vapply(seq_along(n_scale), function(j) {
vapply(seq_len(n_rep),
function(r) simulate_bias(n_scale[j] * n_base, r + 1000 * j),
numeric(1))
}, numeric(n_rep))
sq_err <- bias_mat^2
mse <- colMeans(sq_err)
se_mse <- apply(sq_err, 2, sd) / sqrt(n_rep)
mse_lower <- mse - 1.96 * se_mse
mse_upper <- mse + 1.96 * se_mseMSE vs \(n\). On a log-log scale the empirical MSE falls along a straight line of slope \(-1\), i.e., \(\mathrm{MSE} \propto n^{-1}\), as expected for a \(\sqrt{n}\)-consistent estimator. Vertical bars are 95% normal confidence intervals around each MSE:
plot(n_tot, mse, log = "xy", type = "b", pch = 19,
xlab = "Total sample size n", ylab = "MSE",
ylim = range(c(mse_lower, mse_upper)))
arrows(n_tot, mse_lower, n_tot, mse_upper,
length = 0.03, angle = 90, code = 3)
curve(mse[1] * (x / n_tot[1])^(-1),
from = min(n_tot), to = max(n_tot),
add = TRUE, lty = 2, col = "red")
legend("topright",
legend = c("Empirical MSE", expression(n^{-1} ~ "reference")),
lty = c(1, 2), pch = c(19, NA), col = c("black", "red"),
bty = "n")The MSE above decomposes as \(\mathrm{MSE} = \mathrm{Bias}^2 + \mathrm{Var}\). The two panels below plot the components of that decomposition: on the left, the empirical absolute bias \(|\bar{\hat\tau} - \tau|\), whose magnitude stays below the Monte Carlo resolution at every \(n\) — consistent with the estimator’s finite-sample bias being far smaller than its variance, as expected for a consistent estimator under misspecification — and on the right, the empirical variance, which tracks the \(n^{-1}\) reference and dominates the MSE at every sample size.
abs_bias <- abs(colMeans(bias_mat))
var_hat <- apply(bias_mat, 2, var)
par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
plot(n_tot, abs_bias, log = "xy", type = "b", pch = 19,
xlab = "Total sample size n", ylab = "|empirical bias|",
main = "Bias")
plot(n_tot, var_hat, log = "xy", type = "b", pch = 19,
xlab = "Total sample size n", ylab = "Variance",
main = "Variance")
curve(var_hat[1] * (x / n_tot[1])^(-1),
from = min(n_tot), to = max(n_tot),
add = TRUE, lty = 2, col = "red")
legend("topright",
legend = c("Empirical variance", expression(n^{-1} ~ "reference")),
lty = c(1, 2), pch = c(19, NA), col = c("black", "red"),
bty = "n")4.8 Coverage summary
The three per-example coverage checks reported in Section 4.3, Section 4.5, and Section 4.6 are collected below. All sit near the nominal 95%, confirming that the variance in Proposition 1 yields well-calibrated intervals across the simulation settings considered here.
| Setting | Coverage |
|---|---|
| Homogeneous (Example 1) | 94.9% |
| Heterogeneous covariates (Example 3) | 96.6% |
| Study effects + heteroscedastic arms (Example 4) | 95.5% |
5 Discussion
In this article, we present a federated implementation of ATE estimation across multiple RCTs to facilitate its practical adoption.
An important extension is the application of the proposed framework to multi-site observational studies. In this setting, identification requires conditional exchangeability, \((Y^1,Y^0)\perp\!\!\!\perp A\mid X,H\), rather than randomization. The current G-formula estimator remains consistent under correctly specified linear outcome models, but the robustness to model misspecification established in Proposition 2 no longer holds. Extensions of the framework thus include flexible federated estimation of outcome models and propensity scores to enable doubly robust estimators such as augmented inverse probability weighting (AIPW). Currently, DataSHIELD’s dsBase primarily supports parametric propensity-score estimation through logistic regression via ds.glm.
Further extensions include incorporating external control arms (sites with \(p_k=0\)), which violate site-level positivity and require additional identification assumptions, and generalizing treatment effects to external target populations through federated density-ratio estimation under appropriate transportability and overlap assumptions.
References
Appendix A: Variance
Proof of Proposition 1
Proof. Let \(Z = (H^\top, X^\top)^\top\) and \(\theta_a = (d_a^\top, \beta_a^\top)^\top\). We prove that under Model Equation 5, \(\hat{\tau}\) satisfies \(\sqrt{n}(\hat{\tau} - \tau) \xrightarrow{d} \mathcal{N}(0, V)\), with the general heteroscedastic asymptotic variance:\[V = \mathbb{E}[Z]^\top M_1^{-1} \Omega_1 M_1^{-1} \mathbb{E}[Z] + \mathbb{E}[Z]^\top M_0^{-1} \Omega_0 M_0^{-1} \mathbb{E}[Z] + \mathbb{V}(Z^\top \Delta),\]where \(\Delta = \theta_1 - \theta_0\), \(M_a = \mathbb{E}[\mathbb{I}(A=a) ZZ^\top]\), and \(\Omega_a = \mathbb{E}[\mathbb{I}(A=a) \varepsilon_a^2 ZZ^\top]\).
First, remark that \(\hat{\tau} = \bar{Z}^\top \hat{\Delta}\) and \(\tau = \mathbb{E}[Z]^\top \Delta\), where \(\bar{Z} = \frac{1}{n}\sum_{i=1}^n Z_i\). Thus, \[\begin{aligned} \sqrt{n}(\hat{\tau} - \tau) &= \sqrt{n} \left( \bar{Z}^\top \hat{\Delta} - \mathbb{E}[Z]^\top \Delta \right) \\ &= \sqrt{n} \left( \bar{Z}^\top \hat{\Delta} - \bar{Z}^\top \Delta + \bar{Z}^\top \Delta - \mathbb{E}[Z]^\top \Delta \right) \\ &= \bar{Z}^\top \sqrt{n} ( \hat{\Delta} - \Delta ) + \sqrt{n}(\bar{Z} - \mathbb{E}[Z])^\top \Delta \\ &= \mathbb{E}[Z]^\top \sqrt{n} ( \hat{\Delta} - \Delta ) + \sqrt{n}(\bar{Z} - \mathbb{E}[Z])^\top \Delta + o_p(1), \end{aligned}\] where the last equality follows from Slutsky’s theorem since \(\bar{Z} \xrightarrow{p} \mathbb{E}[Z]\).
Next, we substitute the standard asymptotic linear expansion for the OLS estimators \(\hat{\theta}_a\): \[\sqrt{n}( \hat{\theta}_a - \theta_a ) = M_a^{-1} \frac{1}{\sqrt{n}} \sum_{i=1}^n \mathbb{I}(A_i=a) Z_i \varepsilon_{a,i} + o_p(1).\]
Since \(\hat{\Delta} - \Delta = (\hat{\theta}_1 - \theta_1) - (\hat{\theta}_0 - \theta_0)\), \(\sqrt{n}(\hat{\tau} - \tau)\) rewrites as a scaled sum of independent and identically distributed terms: \[\begin{aligned} \sqrt{n}(\hat{\tau} - \tau) &= \frac{1}{\sqrt{n}} \sum_{i=1}^n \Big[ \mathbb{E}[Z]^\top M_1^{-1} \mathbb{I}(A_i=1) Z_i \varepsilon_{1,i} \\ &\quad - \mathbb{E}[Z]^\top M_0^{-1} \mathbb{I}(A_i=0) Z_i \varepsilon_{0,i} + (Z_i - \mathbb{E}[Z])^\top \Delta \Big] + o_p(1). \end{aligned}\] By the Central Limit Theorem, the asymptotic variance \(V\) is the variance of a single summand. The covariances between these three terms are zero because the treatment groups are mutually exclusive (\(\mathbb{I}(A=1)\mathbb{I}(A=0) = 0\)), and Model Equation 5 is well-specified (\(\mathbb{E}[\varepsilon_a \mid Z] = 0\)), making the errors uncorrelated with \((Z - \mathbb{E}[Z])^\top \Delta\).
Therefore, the variance of the sum is the sum of the individual variances: \[\begin{aligned} V &= \mathbb{V}\left( \mathbb{E}[Z]^\top M_1^{-1} \mathbb{I}(A=1) Z \varepsilon_1 \right) + \mathbb{V}\left( \mathbb{E}[Z]^\top M_0^{-1} \mathbb{I}(A=0) Z \varepsilon_0 \right) + \mathbb{V}\left( (Z - \mathbb{E}[Z])^\top \Delta \right) \\ &= \mathbb{E}[Z]^\top M_1^{-1} \mathbb{E}[\mathbb{I}(A=1) \varepsilon_1^2 Z Z^\top] M_1^{-1} \mathbb{E}[Z] + \mathbb{E}[Z]^\top M_0^{-1} \mathbb{E}[\mathbb{I}(A=0) \varepsilon_0^2 Z Z^\top] M_0^{-1} \mathbb{E}[Z] + \mathbb{V}(Z^\top \Delta) \\ &= \mathbb{E}[Z]^\top M_1^{-1} \Omega_1 M_1^{-1} \mathbb{E}[Z] + \mathbb{E}[Z]^\top M_0^{-1} \Omega_0 M_0^{-1} \mathbb{E}[Z] + \mathbb{V}(Z^\top \Delta). \end{aligned}\] Under homoscedasticity (\(\mathbb{V}(\varepsilon_a \mid Z) = \sigma_a^2\)), we have \(\Omega_a = \sigma_a^2 M_a\), which simplifies the first two terms to \(\sigma_1^2 \mathbb{E}[Z]^\top M_1^{-1} \mathbb{E}[Z]\) and \(\sigma_0^2 \mathbb{E}[Z]^\top M_0^{-1} \mathbb{E}[Z]\), recovering the expression in Proposition 1. ◻
Appendix B: Computing the Variance from Decentralised Data
This section explains how the variance can be estimated in a decentralised data setting. We begin with the last term, \(\mathbb{V}\big((\beta_1-\beta_0)^\top X\big)\), before addressing the two remaining terms.
The Last Term in the Variance Formula
We now focus on estimating \(\mathbb{V}\big((\beta_1-\beta_0)^\top X\big)\); the case of \(\mathbb{V}(Z^\top\Delta)\) follows by an identical argument. A natural estimator is the sample variance of \(z_i = (\hat{\beta}_1 - \hat{\beta}_0)^\top X_i\), given by \[\frac{1}{n-1}\sum_{k=1}^K\sum_{i\in \mathcal{I}_k}\big(z_i-\bar z\big)^2,\] where \(\mathcal{I}_k := \{i : H_i = k\}\) denotes the set of indices belonging to site \(k\). However, this expression is not directly amenable to decentralised computation, since the global mean \(\bar{z}\) appears inside each local sum and prevents a clean decomposition into site-level quantities. To overcome this, we note that \(\bar z = \bar X^\top (\hat{\beta}_1-\hat \beta_0)\), and that by definition \(\bar X_k^\top(\hat{\beta}_1-\hat \beta_0) -\bar z = \hat \tau_k -\hat \tau\). Adding and subtracting \(\bar X_k^\top(\hat{\beta}_1-\hat \beta_0)\) inside each squared term yields \[\frac{1}{n-1}\sum_{k=1}^K\sum_{i\in \mathcal{I}_k}\big(z_i-\bar z\big)^2 = \frac{1}{n-1}\sum_{k=1}^K\sum_{i\in \mathcal{I}_k} \Big(z_i-\bar X_k^\top(\hat{\beta}_1-\hat \beta_0)+ \hat\tau_k - \hat\tau\Big)^2.\] Expanding the square and grouping terms gives \[= \frac{1}{n-1}\left[ \sum_k S_k + \sum_k n_k (\hat \tau_k -\hat\tau)^2 +2\sum_{k=1}^K\sum_{i\in \mathcal{I}_k} \Big(z_i-\bar X_k^\top(\hat{\beta}_1-\hat \beta_0)\Big) \big(\hat\tau_k - \hat\tau\big)\right],\] where we define the site-level sum of squared residuals \(S_k\) as in Equation 10. The cross-product term vanishes because the site-level residuals sum to zero: \[\sum_{i\in \mathcal{I}_k}\Big(z_i-\bar X_k^\top(\hat{\beta}_1-\hat \beta_0)\Big) = 0.\] We therefore obtain the decomposition \[ \frac{1}{n-1}\sum_{k=1}^K\sum_{i\in \mathcal{I}_k}\big(z_i-\bar z\big)^2 = \frac{1}{n-1}\left[ \sum_k S_k + \sum_k n_k (\hat \tau_k -\hat\tau)^2\right]. \tag{11}\]
The key insight is that all quantities involved can be computed locally at each site and subsequently aggregated. Although \(\hat{\beta}_1\) and \(\hat{\beta}_0\) are global parameters, the variance is estimated after fitting the linear models independently using ds.glm, and is therefore only computed once the client (analyst) has broadcast the values of \(\hat{\beta}_1\) and \(\hat{\beta}_0\). The aggregation leading to Equation 11 can thus be carried out in the same round as the aggregation of \(\tau_k\), at the cost of each server further sending \(S_k\).
DataSHIELD implementation
When compute_variance = TRUE, the servers compute \(S_k\) within the localAteDS() function – invoked on the server side by the client-side function .localAte() – and broadcast it alongside \(n_k\) and \(\tau_k\), which are transmitted regardless of the value of compute_variance. Upon receiving these values the client/analyst can thus perform the aggregation in Equation 11. Moreover, the computation of \(S_k\) is performed regardless of the values of \(\texttt{heterogeneous}\) and heteroscedastic_arms.
The Remaining Terms
This section describes how the quantities \(\sigma_1^2\), \(\sigma_0^2\), \(\mathbb{E}[X^\prime]\) and \(M_1^{-1}\) appearing in the variance formula Equation 8 are estimated in a federated manner using the two packages, under heterogeneous = TRUE. We conclude by outlining the adjustments required to compute the variance formula Equation 7.
The Gram Matrices.
A natural estimator of \(M_a^{-1}\) is \[ \Big(\frac{1}{n}\sum_{i=1}^n X^\prime_i (X^\prime_i)^\top \mathbb{I}(A_i=a)\Big)^{-1} = n \underbrace{\Big(\sum_{i=1}^n X^\prime_i (X^\prime_i)^\top \mathbb{I}(A_i=a)\Big)^{-1}}_{:= G_a}, \tag{12}\]
so that only \(G_a\) and \(n\) are needed. The matrix \(G_a\) is returned directly by ds.glm() when the argument viewVarCov = TRUE is set.
The Residual Variances.
When heteroscedastic_arms = TRUE, each arm has its own variance, estimated by \[
\hat\sigma_a^2 = \frac{1}{n^{(a)}-(d+1)}
\sum_{i=1}^n \big(Y_i-\hat \mu_a(X_i)\big)^2 \mathbb{I}(A_i=a),
\tag{13}\]
where \(n^{(a)}\) denotes the number of observations assigned to treatment \(a\). No extra communication is required: the list returned by ds.glm() contains an element dev that is exactly the sum appearing in Equation 13. When heteroscedastic_arms = FALSE, a single variance is shared by both arms and is estimated by \[
\hat\sigma^2 = \frac{1}{n-2(d+1)}\sum_{a=0}^1\sum_{i=1}^n \big(Y_i-\hat \mu_{a}(X_i)\big)^2\mathbb{I}(A_i=a) .
\tag{14}\]
The Covariate Mean.
Each server \(k\) transmits is local the covariate sum \(n_k \bar X_k\), and the client aggregates these according into \[ \frac{1}{n}\sum_k n_k \bar X_k . \tag{15}\]
In the dsFedAte package, \(\bar X_k\) is computed by localAteDS() whenever heterogeneous = TRUE and sent back to the client through the client-side function .localAte(), which is what invokes localAteDS() on the servers.
Study Effects
The variance formula in Equation 7 follows the same reasoning. It amounts to substituting \(X_i^\prime\) in Equation 12 with \(Z_i = (H_i^T, X_i^T)\), where \(H_i\) is one-hot encoded, replacing \(\hat{\mu}_a(X_i)\) in Equation 13 and Equation 14 with \(\hat{\mu}_a(X_i, H_i)\), and replacing \(\bar{X}_k\) in Equation 15 with \(\bar{Z}_k\).
Homogeneous Covariates
The estimator in Equation 9 admits a straightforward federated implementation. Estimation of \(\sigma_a^2\) follows the procedure described above, leaving \(p\) as the only remaining quantity to be estimated. A natural estimator is \[\hat p := \frac{1}{n}\sum_{k=1}^K n_k^{(1)},\] where \(n_k^{(1)}\) denotes the local treated count, reported to the client upon invocation of localAteDS().
Appendix C: Misspecified linear G-formula asymptotic normality
Proof. For each center \(k\) and treatment arm \(w\in\{0,1\}\), define the index set \(\mathcal{C}_k^{(w)}=\{i:H_i=k,\,W_i=w\}\) with cardinality \(n_k^{(w)}=|\mathcal{C}_k^{(w)}|\). Let \(n_k=n_k^{(0)}+n_k^{(1)}\) denote the total number of individuals in center \(k\), and let \(\hat{p}_k=n_k^{(1)}/n_k\) be the observed treatment proportion within that center. For any variable \(Z\in\{X,Y\}\), write \(\bar{Z}_k^{(w)}\) for the sample mean of \(Z\) over \(\mathcal{C}_k^{(w)}\), and let \(\bar{X}_k\) denote the marginal sample mean of \(X\) over all individuals in center \(k\).
First, as stated in Lemma 1, \(\hat{\tau}\), defined in Equation 3, can be expressed as \[ \hat\tau=\sum_{k=1}^K\frac{n_k}{n}\Big\{\bar Y_k^{(1)}-\bar Y_k^{(0)} -\big(\bar X_k^{(1)}-\bar X_k^{(0)}\big)^\top\hat{\bar\beta}_k\Big\}, \tag{16}\]
where \(\hat{\bar\beta}_k:=(1-\hat p_k)\hat\beta^{(1)}+\hat p_k\hat\beta^{(0)}\).
Let \(( d_w^\star, \beta_w^\star)\), the population counterpart of Equation 4, such that \[ ( d_w^\star, \beta_w^\star) = \operatorname*{argmin}_{ d,\, \beta} \mathbb{E}\Big[ \bigl(Y - d^\top H - \beta^\top X\bigr)^2\, \Big|\, W=w\Big], \tag{17}\]
and \(\bar\beta_k=(1-p_k)\beta_1^\star+p_k\beta_0^\star\). Then, we have \[ \hat{\tau}-\tau = \underbrace{\sum_{k=1}^K \frac{n_k}{n} \Big\{\big(\bar X_k^{(1)}-\bar X_k^{(0)}\big)^\top \big(\bar \beta_k-\hat{\bar\beta}_k\big)\Big\}}_{=:A_n} +\underbrace{\sum_{k=1}^K\frac{n_k}{n} \Big\{\bar Y_k^{(1)}-\bar Y_k^{(0)} -\big(\bar X_k^{(1)}-\bar X_k^{(0)}\big)^\top \bar\beta_k\Big\}}_{=:B_n} -\tau. \tag{18}\]
Similar to Theorem 1.3 of Wager (2024), the Huber–White analysis of misspecified linear regression implies that \(\hat{\beta}^{(w)} \xrightarrow{p} \beta_w^\star\), provided the design matrix for \((H^\top, X^\top)^\top\) is non-singular. Furthermore, by the Weak Law of Large Numbers, \(\hat{p}_k \xrightarrow{p} p_k\). By the Continuous Mapping Theorem, their convex combination converges, meaning \(\hat{\bar\beta}_k \xrightarrow{p} \bar\beta_k\), and thus \((\bar \beta_k-\hat{\bar\beta}_k) = o_P(1)\).
Furthermore, under within-center randomization (\(X\perp\!\!\!\perp A\mid H\)), covariates are exchangeable by treatment groups, so \(\bar X_k^{(1)}\) and \(\bar X_k^{(0)}\) both converge to \(\mathbb{E}[X \mid H=k]\). By the Central Limit Theorem, their difference \(\sqrt{n_k}\,(\bar X_k^{(1)}-\bar X_k^{(0)})\to \mathcal N(0,\Sigma_k)\). Because \(n_k/n \xrightarrow{p} \mathbb{P}(H=k) > 0\), the global scaled difference \(\sqrt{n}\,(\bar X_k^{(1)}-\bar X_k^{(0)})=O_P(1)\). Therefore, \(\sqrt{n} A_n = O_P(1) \cdot o_P(1) = o_P(1)\).
Finally, remark that \(B_n\) in Equation 18 has the structure of a stratified estimator of the form studied in Theorem 2.1 of Wager (2024), applied to a modified outcome. Specifically, the transformed potential outcomes and their observed counterpart are defined as \[ \tilde Y(w)=Y(w)-X^\top\bar\beta_H, \qquad \tilde Y_i(W_i)=Y_i-X_i^\top\bar\beta_{H_i}, \tag{19}\]
and let \(\bar{\tilde Y}_k^{(w)}=\frac{1}{n_k}\sum_{i\in \mathcal{C}_k^{(w)}} \tilde Y_i(w)\). With this notation, we have \[B_n -\tau = \sum_{k=1}^K\frac{n_k}{n}\big(\bar{\tilde Y}_k^{(1)}-\bar{\tilde Y}_k^{(0)}\big)-\tau.\] Theorem 2.1 of Wager (2024) applies directly because the transformed variables \(\tilde Y_i(w)\) satisfy the requisite conditions of SUTVA, bounded second moments, and \(W \perp\!\!\!\perp (\tilde Y(0), \tilde Y(1)) \mid H\), i.e., \[\begin{aligned} \mathbb{E}[\tilde Y(1)-\tilde Y(0)]&=\mathbb{E}[Y(1)-Y(0)]=\tau,\\ \mathbb{E}[\tilde Y(1)-\tilde Y(0)\mid H=k]&=\mathbb{E}[Y(1)-Y(0)\mid H=k]=\tau_k. \end{aligned}\] and the tuple \(\{(X_i,\,\tilde Y_i(0),\,\tilde Y_i(1),\,W_i)\}\) satisfies all conditions required by that theorem. Therefore, \[\sqrt{n}\left(B_n - \tau\right) \to \mathcal N(0,V^\star),\] with \(V^\star = \mathbb{V}_{P_H}(\tau_H) + \mathbb{E}_{P_H}[V_H]\), where \(V_H = \frac{\mathbb{V}(\tilde Y(1) \mid H)}{p_H} + \frac{\mathbb{V}(\tilde Y(0) \mid H)}{1 - p_H}.\) With Slutsky’s theorem, this concludes that \[\sqrt{n}(\hat{\tau} - \tau) \xrightarrow{d} \mathcal N(0, V^\star).\]
Finally, the unadjusted stratified difference-in-means estimator \[\hat\tau_\mathrm{DM} = \sum_{k=1}^K \frac{n_k}{n} \left( \bar{Y}_k^{(1)} - \bar{Y}_k^{(0)} \right)\] has an asymptotic variance of \(V_{\mathrm{DM}} = \mathbb{V}_{P_H}(\tau_H) + \mathbb{E}_{P_H}[V_H^{\mathrm{DM}}]\), where \(V_H^{\mathrm{DM}} = \frac{\mathbb{V}(Y(1) \mid H)}{p_H} + \frac{\mathbb{V}(Y(0) \mid H)}{1 - p_H}\). By definition of \(( d_w^\star, \beta_w^\star)\) in Equation 17, the parameters minimize the mean squared error such that:\[\mathbb{E}\left[ (Y(w) - {d_w^\star}^\top H - X^\top \beta_w^\star)^2 \mid H \right] \leq \mathbb{E}\left[ (Y(w) - \mathbb{E}[Y(w) \mid H])^2 \mid H \right] = \mathbb{V}(Y(w) \mid H).\] This implies \(\mathbb{V}(\tilde Y(w) \mid H) \leq \mathbb{V}(Y(w) \mid H)\), which yields \(V^\star \leq V_{\mathrm{DM}}\), concluding the proof. ◻
Lemma 1. The estimator \(\hat{\tau}\) can be written in the closed form given in Equation 16.
Proof. The objective in Equation 4 splits over centers, \(\sum_k\sum_{i\in\mathcal{C}_k^{(w)}}(Y_i-d_k-X_i^\top\beta)^2\), so the optimality condition for \(\hat d_k\) is \(-2n_k^{(w)}\{\bar Y_k^{(w)}-\hat d_k-(\bar X_k^{(w)})^\top\beta\}=0\), whence \[ \hat d_k^{(w)}=\bar Y_k^{(w)}-\big(\bar X_k^{(w)}\big)^\top\hat\beta^{(w)} . \tag{20}\]
Substituting Equation 20 into \(\hat \tau\) yields, \[\begin{aligned} \hat \tau &=\sum_k\frac{n_k}{n}\Big(\hat d_k^{(1)}-\hat d_k^{(0)}+\bar X_k^\top\big(\hat\beta^{(1)}-\hat \beta^{(0)}\big)\Big) \\ &=\sum_k\frac{n_k}{n}\Big(\bar Y_k^{(1)}-\bar Y_k^{(0)}+\big(\bar X_k-\bar X_k^{(1)}\big)^\top\hat\beta^{(1)}-\big(\bar X_k-\bar X_k^{(0)}\big)^\top\hat \beta^{(0)}\Big). \end{aligned}\] Since \(\bar X_k=\hat p_k\bar X_k^{(1)}+(1-\hat p_k)\bar X_k^{(0)}\) we have \(\bar X_k-\bar X_k^{(1)}=-(1-\hat p_k)(\bar X_k^{(1)}-\bar X_k^{(0)})\) and \(\bar X_k-\bar X_k^{(0)}=\hat p_k(\bar X_k^{(1)}-\bar X_k^{(0)})\); collecting the slope terms gives Equation 16. ◻
Appendix D: IRLS vs FedAvg
Recent approaches to federated causal inference employ varying optimization strategies for nuisance parameter estimation. For instance, Khellaf et al. (2024) estimate regression functions using a multi-shot Federated Averaging (FedAvg) procedure restricted to a single local update per communication round. This configuration corresponds to the standard recursion of centralized gradient descent: \[\theta^{(t+1)} = \theta^{(t)} - \eta \sum_{k=1}^K \frac{n_k}{n} \nabla \mathcal{L}_k(\theta^{(t)}),\] where \(\eta\) is the learning rate, \(\theta^{(t)}\) is the global parameter at round \(t\), and \(\nabla \mathcal{L}_k(\theta^{(t)})\) is the local gradient of the empirical loss computed at site \(k\).
In contrast, DataSHIELD implements generalized linear models (via the ds.glm function) using a distributed Iteratively Reweighted Least Squares (IRLS) algorithm. In this approach, the central server broadcasts the current parameter estimates at each iteration. Each site then computes local working responses and information matrices based on its local data. The server aggregates these local matrices to compute a Newton-Raphson update: \[\theta^{(t+1)} = \theta^{(t)} - \left( \sum_{k=1}^K \nabla^2 \mathcal{L}_k(\theta^{(t)}) \right)^{-1} \sum_{k=1}^K \nabla \mathcal{L}_k(\theta^{(t)}),\] where \(\nabla^2 \mathcal{L}_k(\theta^{(t)})\) denotes the local Hessian (or empirical Fisher information matrix) evaluated at site \(k\). This second-order method typically converges in fewer communication rounds than first-order gradient approaches like FedAvg, at the cost of larger amounts of float exchanged per round (\(O(d^2)\)).
Furthermore, in the specific context of linear regression with a quadratic loss function, the estimation admits a closed-form solution, enabling a one-shot federated procedure. Each site \(k\) computes its local uncentered covariance matrix \(M_{k,a} = \sum_{i \in \mathcal{C}_k^{(a)}} Z_i Z_i^\top\) and cross-product vector \(\nabla_{k,a} = \sum_{i \in \mathcal{C}_k^{(a)}} Z_i Y_i\) for each treatment arm \(a\). The central server then aggregates these sufficient statistics to compute the global OLS estimator: \[\hat\theta_a = \left(\sum_{k=1}^K M_{k,a}\right)^{-1}\left(\sum_{k=1}^K \nabla_{k,a}\right).\] This one-shot aggregation retrieves the centralized pooled solution without requiring iterative communication. It is equivalent to the FedAvg algorithm limit as the number of communication rounds \(T\) goes to infinity.
Session information
sessionInfo()
#> R version 4.6.0 (2026-04-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.12.0
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.0 LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
#> [4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
#> [7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
#> [10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats graphics grDevices datasets utils methods base
#>
#> other attached packages:
#> [1] MASS_7.3-66 DSLite_1.4.1 rly_1.7.8
#> [4] DSI_1.8.0 R6_2.6.1 progress_1.2.3
#> [7] dsFedAte_0.1.0 dsFedAteClient_0.1.0
#>
#> loaded via a namespace (and not attached):
#> [1] shape_1.4.6.1 xfun_0.61 lattice_0.22-9
#> [4] gamlss_5.5-5 vctrs_0.7.3 tools_4.6.0
#> [7] childsds_0.9.11 Rdpack_2.6.6 generics_0.1.4
#> [10] parallel_4.6.0 tibble_3.3.1 pan_2.0
#> [13] pkgconfig_2.0.3 jomo_2.7-6 Matrix_1.7-5
#> [16] data.table_1.18.6.1 assertthat_0.2.1 lifecycle_1.0.5
#> [19] compiler_4.6.0 deldir_2.0-4 textshaping_1.0.5
#> [22] codetools_0.2-20 htmltools_0.5.9 yaml_2.3.12
#> [25] glmnet_5.1 mice_3.19.0 pillar_1.11.1
#> [28] nloptr_2.2.1 crayon_1.5.3 tidyr_1.3.2
#> [31] reformulas_0.4.4 iterators_1.0.14 rpart_4.1.27
#> [34] boot_1.3-32 foreach_1.5.2 mitml_0.4-5
#> [37] nlme_3.1-169 tidyselect_1.2.1 digest_0.6.39
#> [40] dplyr_1.2.1 purrr_1.2.2 splines_4.6.0
#> [43] gamlss.dist_6.1-11 fastmap_1.2.0 grid_4.6.0
#> [46] gamlss.data_6.0-7 cli_3.6.6 magrittr_2.0.5
#> [49] survival_3.8-6 broom_1.0.13 prettyunits_1.2.0
#> [52] backports_1.5.1 dsBaseClient_6.3.6.9000 rmarkdown_2.32
#> [55] nnet_7.3-20 interp_1.1-6 lme4_2.0-6
#> [58] hms_1.1.4 evaluate_1.0.5 knitr_1.52
#> [61] rbibutils_2.4.1 rlang_1.3.0 Rcpp_1.1.2
#> [64] glue_1.8.1 dsBase_6.3.6.9000 renv_1.2.3
#> [67] svglite_2.2.2 minqa_1.2.8 jsonlite_2.0.0
#> [70] systemfonts_1.3.2Reuse
Citation
@article{andrade2026,
author = {{Francisco Andrade†} and {Rémi Khellaf†} and Josse, Julie},
title = {Federated {Average} {Treatment} {Effect} {Estimation} for
{Multi-Site} {RCTs} with {DataSHIELD}},
journal = {Computo},
date = {2026-11-15},
doi = {10.5072/computo.0000},
issn = {2824-7795},
langid = {en},
abstract = {We introduce `dsFedAte` and `dsFedAteClient`, two
companion R packages for federated estimation of the average
treatment effect (ATE) from multiple randomized controlled trials
(RCTs), without sharing individual-level data. Built on the
open-source DataSHIELD privacy-preserving infrastructure, they
implement a covariate-adjusted G-formula estimator accommodating
heterogeneous covariate distributions and study effects. Unlike
iterative federated optimization methods, our approach fits
arm-specific linear outcome models in a single communication round
by aggregating local sufficient statistics, yielding estimates
identical to those obtained from centrally pooled data. The entire
analysis is accessible through a single client-side function,
`ds.EstimateAte()`. Beyond implementation, we also present
methodological contributions. First, we derive the asymptotic
variance of the ATE estimator, accounting for heterogeneous
covariate distributions and study effects, and express its estimator
in terms of locally aggregable quantities, enabling federated
confidence intervals equivalent to those obtained from pooled data.
Second, we establish consistency and asymptotic normality under
misspecified linear outcome models, showing that covariate
adjustment is asymptotically at least as efficient as the unadjusted
stratified difference-in-means estimator. We illustrate the packages
through reproducible examples using the DSLite simulation
environment, covering homogeneous and heterogeneous populations,
DataSHIELD disclosure controls, and adjustment for study effects. A
simulation study validates the theoretical results and demonstrates
nominal confidence interval coverage.}
}