| Title: | High-Performance Frequentist and Bayesian Small Area Estimation in R |
|---|---|
| Description: | High-performance Small Area Estimation (SAE) in R, implementing frequentist EBLUP models via compiled C++ and Bayesian hierarchical models via 'INLA' (Integrated Nested Laplace Approximations) or, optionally, full MCMC with 'NumPyro' (Phan et al., 2019) <doi:10.48550/arXiv.1912.11554> on 'JAX' (CPU or NVIDIA GPU). Frequentist models include the area-level Fay-Herriot model (Fay and Herriot, 1979 <doi:10.1080/01621459.1979.10482505>), spatial Fay-Herriot (Pratesi and Salvati, 2008 <doi:10.1007/s10260-007-0061-9>), spatio-temporal Fay-Herriot (Marhuenda et al., 2013 <doi:10.1016/j.csda.2012.09.002>), unit-level Battese-Harter-Fuller (Battese et al., 1988 <doi:10.1080/01621459.1988.10478561>), and two-fold subarea models (Torabi and Rao, 2014 <doi:10.1016/j.jmva.2014.02.001>) for nested area-subarea hierarchies. Bayesian models use 'INLA' (Rue et al., 2009 <doi:10.1111/j.1467-9868.2008.00700.x>), supporting 6 likelihood families (Gaussian, Beta, Binomial, Poisson, Negative Binomial, Gamma), spatial structures (BYM2, Besag ICAR), temporal dynamics (RW1, RW2, AR1), and spatio-temporal interactions. Key features include analytical and bootstrap MSE estimation, benchmarking to aggregate targets (Rao and Molina, 2015 <doi:10.1002/9781118735855>), automatic handling of unsampled domains, and S3 methods for summaries, diagnostics and plots. |
| Authors: | Ridson Al Farizal P [aut, cre, cph] (ORCID: <https://orcid.org/0000-0003-0617-0214>), Azka Ubaidillah [aut] (ORCID: <https://orcid.org/0000-0002-3597-0459>) |
| Maintainer: | Ridson Al Farizal P <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.0 |
| Built: | 2026-10-14 18:59:05 UTC |
| Source: | https://github.com/ridsonap/fastsae |
Categorizes small area estimates into publication reliability tiers based on their relative standard error (RSE, %). The default thresholds follow the criteria used by BPS-Statistics Indonesia:
Reliable (): suitable for publication.
Use with caution (): publish with a
cautionary note on sampling variability.
Unreliable (): suppress or aggregate to a higher level.
Other agencies use other cut-offs (for example 25% and 50% at the Australian Bureau of
Statistics); set thresholds accordingly.
add_reliability_flags(object, rse_col = "rse", thresholds = c(25, 50))add_reliability_flags(object, rse_col = "rse", thresholds = c(25, 50))
object |
A |
rse_col |
Character string specifying the name of the RSE column. Default is |
thresholds |
Numeric vector of length 2 with the RSE (%) cut-offs. Default is |
The estimation table (a data frame) with an additional factor column reliability.
library(fastsae) data(mys) fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) df_flagged <- add_reliability_flags(fit_fh) table(df_flagged$reliability)library(fastsae) data(mys) fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) df_flagged <- add_reliability_flags(fit_fh) table(df_flagged$reliability)
Creates diagnostic and comparison plots for Small Area Estimation (SAE)
models fitted with fastsae. This extends the generic
autoplot from ggplot2.
## S3 method for class 'fastsae' autoplot( object, type = c("comparison", "ribbon", "mse", "estimates", "scatter", "rse", "map"), ... ) ## S3 method for class 'list' autoplot(object, type = c("comparison", "mse", "scatter", "map"), ...)## S3 method for class 'fastsae' autoplot( object, type = c("comparison", "ribbon", "mse", "estimates", "scatter", "rse", "map"), ... ) ## S3 method for class 'list' autoplot(object, type = c("comparison", "mse", "scatter", "map"), ...)
object |
An object of class |
type |
Type of plot to create.
|
... |
Additional arguments passed to internal plotting helpers
(e.g. |
A ggplot object.
library(fastsae) # Single model plot fit_fh <- eblup_fh(y ~ x1 + x2 + x3, data = mys, vardir = "vardir") autoplot(fit_fh, type = "estimates") autoplot(fit_fh, type = "rse") # Compare two models fit_sfh <- eblup_sfh(y ~ x1 + x2 + x3, data = mys, vardir = "vardir", W = mys_proxmat) autoplot(list("Fay-Herriot" = fit_fh, "Spatial FH" = fit_sfh), type = "comparison")library(fastsae) # Single model plot fit_fh <- eblup_fh(y ~ x1 + x2 + x3, data = mys, vardir = "vardir") autoplot(fit_fh, type = "estimates") autoplot(fit_fh, type = "rse") # Compare two models fit_sfh <- eblup_sfh(y ~ x1 + x2 + x3, data = mys, vardir = "vardir", W = mys_proxmat) autoplot(list("Fay-Herriot" = fit_fh, "Spatial FH" = fit_sfh), type = "comparison")
Generates diagnostic visual inspections for small area estimation models evaluated
via diagnose.
## S3 method for class 'fastsae_diagnose' autoplot( object, type = c("all", "calibration", "rse", "residuals", "qq", "pit", "cpo"), ... )## S3 method for class 'fastsae_diagnose' autoplot( object, type = c("all", "calibration", "rse", "residuals", "qq", "pit", "cpo"), ... )
object |
An object of class |
type |
Character string indicating the diagnostic plot type:
|
... |
Additional arguments passed to ggplot2 layers. |
A ggplot object.
Calibrates small area model predictions (from hb_area, eblup_fh,
eblup_sfh, eblup_stfh, or eblup_bhf) so that their weighted
aggregate matches known benchmark targets at higher administrative levels (e.g. provincial
or national totals/means), as required in official statistics production.
Supports:
Single-Stage Benchmarking: Calibrates small areas directly to an aggregate target
(either globally or within sub-regions/provinces via group).
Two-Stage Hierarchical Benchmarking (Rao and Molina, 2015, Sec 10.4; Steorts et al., 2014):
Calibrates small areas (e.g. 500 Kabupaten/Kota) within overarching groups (e.g. 34 Provinces)
while simultaneously harmonizing the provincial aggregates to match an overarching National Target
(national_target). Guarantees simultaneous mathematical consistency across all administrative tiers:
and
.
Methods implemented:
"ratio": Proportional / multiplicative adjustment. Preserves area proportions and non-negativity (You and Rao, 2002; Rao and Molina, 2015).
"difference": Uniform additive adjustment (Rao and Molina, 2015, Section 10.3).
"optimal": Variance-weighted quadratic loss benchmarking (Datta et al., 2011; Steorts et al., 2014).
Domains with higher MSE absorb larger adjustments while precise domains remain minimally perturbed.
"logit": Logit-scale additive shift for bounded indicators (Berg and Fuller, 2014).
benchmark_sae(object, ...) ## S3 method for class 'fastsae' benchmark_sae( object, target = NULL, weight = NULL, method = c("ratio", "difference", "optimal", "logit"), group = NULL, type = c("mean", "total"), national_target = NULL, outer_target = NULL, ... ) ## Default S3 method: benchmark_sae( object, target = NULL, weight = NULL, method = c("ratio", "difference", "optimal", "logit"), group = NULL, type = c("mean", "total"), national_target = NULL, outer_target = NULL, ... ) ## S3 method for class 'fastsae_benchmark' print(x, all_groups = FALSE, ...) ## S3 method for class 'fastsae_benchmark' summary(object, ...) ## S3 method for class 'fastsae_benchmark' autoplot(object, ...) ## S3 method for class 'fastsae_benchmark' plot(x, y = NULL, ...)benchmark_sae(object, ...) ## S3 method for class 'fastsae' benchmark_sae( object, target = NULL, weight = NULL, method = c("ratio", "difference", "optimal", "logit"), group = NULL, type = c("mean", "total"), national_target = NULL, outer_target = NULL, ... ) ## Default S3 method: benchmark_sae( object, target = NULL, weight = NULL, method = c("ratio", "difference", "optimal", "logit"), group = NULL, type = c("mean", "total"), national_target = NULL, outer_target = NULL, ... ) ## S3 method for class 'fastsae_benchmark' print(x, all_groups = FALSE, ...) ## S3 method for class 'fastsae_benchmark' summary(object, ...) ## S3 method for class 'fastsae_benchmark' autoplot(object, ...) ## S3 method for class 'fastsae_benchmark' plot(x, y = NULL, ...)
object |
A fitted |
... |
Additional arguments passed to methods. |
target |
Numeric value, named vector, or data frame specifying the benchmark
target(s)
|
weight |
Optional numeric vector or character string naming the domain
benchmark weight column in |
method |
Character string specifying the benchmarking calibration method:
|
group |
Optional vector or character string naming the grouping/stratum column (e.g., province or region) for multi-level hierarchical calibration. |
type |
Character string: |
national_target |
Optional numeric scalar defining the overarching national target
(Level 0) for Two-Stage Hierarchical Benchmarking. When provided alongside |
outer_target |
Alias for |
x |
An object of class |
all_groups |
Logical; if |
y |
Ignored argument for compatibility with the generic |
An object of class c("fastsae_benchmark", "data.frame") containing:
domain: Domain identifier.
group: Stratum / overarching group identifier (if specified).
weight: Benchmark weight .
original: Model-based prediction before benchmarking ().
benchmarked: Calibrated estimate satisfying the benchmark constraint ().
adjustment: Absolute adjustment ().
rel_adjustment_pct: Relative adjustment percentage (%).
target: Corresponding group benchmark target .
national_target: Overarching national target (if two-stage hierarchical).
Rao, J. N. K., and Molina, I. (2015). Small Area Estimation (2nd ed.). John Wiley & Sons. Chapter 10: "Benchmarking and Other Practical Issues", pp. 297-315.
You, Y., and Rao, J. N. K. (2002). A pseudo-empirical best linear unbiased prediction approach to small area estimation using survey weights. The Canadian Journal of Statistics, 30(3), 431-439.
Steorts, R. C., Hall, P., and Ghosh, M. (2014). General benchmarking under quadratic loss with applications to small area estimation. Journal of Survey Statistics and Methodology, 2(2), 173-193.
Datta, G. S., Ghosh, M., Steorts, R., and Maples, J. (2011). Bayesian benchmarking with applications to small area estimation. Test, 20(3), 574-588.
Berg, E., and Fuller, W. A. (2014). Small area prediction of proportions with a constrained multinomial logit model. Journal of Survey Statistics and Methodology, 2(3), 256-283.
library(fastsae) data(mys) # Assign province groups for hierarchical calibration example mys$province <- rep(c("Prov_A", "Prov_B", "Prov_C"), length.out = nrow(mys)) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) # 2. Ratio benchmarking to overall target (e.g. target = 6.5) bm_ratio <- benchmark_sae(fit_fh, target = 6.5, method = "ratio") head(bm_ratio) # 3. Two-Stage Hierarchical Calibration (e.g. Regency -> Province -> National) # Calibrate domains within provinces while matching overarching national target: bm_hier <- benchmark_sae( fit_fh, group = "province", weight = mys$n, national_target = 6.2, method = "ratio" ) print(bm_hier)library(fastsae) data(mys) # Assign province groups for hierarchical calibration example mys$province <- rep(c("Prov_A", "Prov_B", "Prov_C"), length.out = nrow(mys)) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) # 2. Ratio benchmarking to overall target (e.g. target = 6.5) bm_ratio <- benchmark_sae(fit_fh, target = 6.5, method = "ratio") head(bm_ratio) # 3. Two-Stage Hierarchical Calibration (e.g. Regency -> Province -> National) # Calibrate domains within provinces while matching overarching national target: bm_hier <- benchmark_sae( fit_fh, group = "province", weight = mys$n, national_target = 6.2, method = "ratio" ) print(bm_hier)
Checks that hb_area(engine = "jax") can run: the package reticulate
and a Python with the modules jax and numpyro. It looks for the
r-numpyro-gpu virtualenv (see setup_numpyro_env) or any
Python already configured for reticulate. The check never installs or
downloads anything: the managed ('uv') Python of reticulate is not
provisioned unless the RETICULATE_USE_MANAGED_VENV environment variable is set.
check_numpyro_available(device = "auto")check_numpyro_available(device = "auto")
device |
Character: |
Logical indicating whether the environment is properly configured.
check_numpyro_available()check_numpyro_available()
Extract coefficients from a fastsae object
## S3 method for class 'fastsae' coef(object, ...)## S3 method for class 'fastsae' coef(object, ...)
object |
An object of class |
... |
Additional arguments. |
Named vector of estimated coefficients.
Provides a comprehensive evaluation and concordance comparison between two fitted Small Area Estimation (SAE) models (e.g. comparing Classical Fay-Herriot vs Spatial Fay-Herriot, Area-level vs Unit-level BHF, or EBLUP vs HB).
Computes empirical agreement and efficiency metrics including:
Pearson linear correlation () and Spearman rank correlation ().
Mean Absolute Difference (MAE) and Root Mean Squared Difference (RMSD).
Relative efficiency metrics: Mean MSE ratio (),
and the proportion of domains where Model 2 achieves greater precision.
Average Relative Standard Error (RSE %) across models and precision gains.
compare_sae(model1, model2 = NULL, names = NULL, thresholds = c(25, 50), ...) ## Default S3 method: compare_sae(model1, model2 = NULL, names = NULL, thresholds = c(25, 50), ...) ## S3 method for class 'fastsae_comparison' print(x, ...) ## S3 method for class 'fastsae_comparison' summary(object, ...) ## S3 method for class 'fastsae_comparison' plot(x, y = NULL, ...) ## S3 method for class 'fastsae_comparison' autoplot( object, type = c("scatter", "comparison", "difference", "mse", "rse"), title = NULL, ... )compare_sae(model1, model2 = NULL, names = NULL, thresholds = c(25, 50), ...) ## Default S3 method: compare_sae(model1, model2 = NULL, names = NULL, thresholds = c(25, 50), ...) ## S3 method for class 'fastsae_comparison' print(x, ...) ## S3 method for class 'fastsae_comparison' summary(object, ...) ## S3 method for class 'fastsae_comparison' plot(x, y = NULL, ...) ## S3 method for class 'fastsae_comparison' autoplot( object, type = c("scatter", "comparison", "difference", "mse", "rse"), title = NULL, ... )
model1 |
A fitted |
model2 |
A second fitted |
names |
Optional character vector of length 2 specifying descriptive labels for the models. Default is inferred from model types or call arguments. |
thresholds |
Numeric vector of length 2 with the RSE (%) cut-offs drawn in
|
... |
Additional arguments. |
x |
An object of class |
object |
An object of class |
y |
Ignored argument for compatibility with the generic |
type |
Character string indicating comparison plot type: |
title |
Optional character string specifying a custom plot title. |
An S3 object of class fastsae_comparison containing:
metrics: A data frame of overall concordance and efficiency statistics.
data: A domain-level data frame with aligned estimates, MSE, and RSE values.
names: Vector of the two model names.
thresholds: The RSE thresholds used.
autoplot.fastsae_comparison, map_sae
library(fastsae) data(mys) # Fit two models fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) fit_sfh <- eblup_sfh(y ~ x1 + x2, vardir = "vardir", data = mys, W = mys_proxmat) # Compare models comp <- compare_sae(fit_fh, fit_sfh, names = c("FH", "Spatial FH")) print(comp) summary(comp) # Plot comparison autoplot(comp, type = "scatter") autoplot(comp, type = "difference")library(fastsae) data(mys) # Fit two models fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) fit_sfh <- eblup_sfh(y ~ x1 + x2, vardir = "vardir", data = mys, W = mys_proxmat) # Compare models comp <- compare_sae(fit_fh, fit_sfh, names = c("FH", "Spatial FH")) print(comp) summary(comp) # Plot comparison autoplot(comp, type = "scatter") autoplot(comp, type = "difference")
Survey and satellite data for corn and soy beans in 12 Iowa counties, originally obtained from the 1978 June Enumerative Survey of the U.S. Department of Agriculture and from LANDSAT satellite observations during the 1978 growing season.
data(cornsoybean)data(cornsoybean)
A data frame with 37 observations on the following 5 variables:
numeric county code.
reported hectares of corn from the survey.
reported hectares of soy beans from the survey.
number of pixels of corn in the sample segment within county, from satellite data.
number of pixels of soy beans in the sample segment within county, from satellite data.
This dataset is included for demonstration purposes and is originally provided in the sae package.
Battese, G.E., Harter, R.M., and Fuller, W.A. (1988). *An Error-Components Model for Prediction of County Crop Areas Using Survey and Satellite Data.* *Journal of the American Statistical Association*, 83, 28–36.
County means of number of pixels per segment of corn and soy beans,
from satellite data, for 12 counties in Iowa. The dataset includes
population size, sample size, and means of auxiliary variables used in
the dataset cornsoybean.
data(cornsoybeanmeans)data(cornsoybeanmeans)
A data frame with 12 observations on the following 6 variables:
numeric county code.
name of the county.
number of sample segments in the county (sample size).
number of population segments in the county (population size).
mean number of corn pixels per segment in the county.
mean number of soy beans pixels per segment in the county.
This dataset is provided for demonstration purposes and is originally distributed with the sae package.
Battese, G.E., Harter, R.M., and Fuller, W.A. (1988). *An Error-Components Model for Prediction of County Crop Areas Using Survey and Satellite Data.* *Journal of the American Statistical Association*, 83, 28–36.
Constructs spatial proximity, contiguity, and weight matrices ()
from spatial data (sf polygon or point objects, coordinate matrices, or neighbor lists).
Supports Queen and Rook contiguity, -nearest neighbors (-NN),
distance bands, and inverse distance weighting (IDW), with automatic fallback
handling for isolated islands and disconnected domains.
create_weights( data, method = c("queen", "rook", "knn", "distance", "idw"), style = c("W", "B", "C", "U", "minmax"), k = 4, d_max = NULL, alpha = 1, island_fallback = TRUE, k_fallback = 1, domain = NULL )create_weights( data, method = c("queen", "rook", "knn", "distance", "idw"), style = c("W", "B", "C", "U", "minmax"), k = 4, d_max = NULL, alpha = 1, island_fallback = TRUE, k_fallback = 1, domain = NULL )
data |
An |
method |
Character string specifying the spatial weight method:
|
style |
Character string specifying the normalization style:
|
k |
Integer. Number of nearest neighbors when |
d_max |
Numeric. Distance threshold when |
alpha |
Numeric. Distance decay power for |
island_fallback |
Logical. If |
k_fallback |
Integer. Number of nearest neighbors to connect for isolated islands
when |
domain |
Optional vector, column name, or one-sided formula referencing domain IDs. If provided, used as row and column names for the resulting matrix. |
When working with real administrative boundaries (such as Indonesian provinces, regencies,
or municipalities), island regencies (e.g. Kepulauan Seribu, Natuna, Sabang, Mentawai,
Sangihe) lack contiguous land borders. If island_fallback = TRUE, create_weights
detects these zero-neighbor domains and connects each to its closest k_fallback
neighbor(s) based on centroid distances, ensuring a connected spatial graph without
computational singularities.
A square numeric matrix of class c("fastsae_weights", "matrix") of dimension
. Attributes include method, style, n_domains,
n_islands, and call.
## Not run: if (requireNamespace("sf", quietly = TRUE)) { # Assuming 'data_kab' is an sf polygon object: W_queen <- create_weights(data_kab, method = "queen", style = "W") W_knn <- create_weights(data_kab, method = "knn", k = 5, style = "W") W_bin <- create_weights(data_kab, method = "queen", style = "B") } ## End(Not run) # Create spatial weights from 2D coordinates coords <- matrix(runif(40), ncol = 2) W_coord <- create_weights(coords, method = "knn", k = 3, style = "W") dim(W_coord)## Not run: if (requireNamespace("sf", quietly = TRUE)) { # Assuming 'data_kab' is an sf polygon object: W_queen <- create_weights(data_kab, method = "queen", style = "W") W_knn <- create_weights(data_kab, method = "knn", k = 5, style = "W") W_bin <- create_weights(data_kab, method = "queen", style = "B") } ## End(Not run) # Create spatial weights from 2D coordinates coords <- matrix(runif(40), ncol = 2) W_coord <- create_weights(coords, method = "knn", k = 3, style = "W") dim(W_coord)
Conducts a comprehensive diagnostic evaluation of small area estimation models (HB or EBLUP). Evaluates estimation precision, efficiency gains over direct estimators, external calibration and bias diagnostics (Brown et al., 2001), goodness-of-fit tests, and residual spatial autocorrelation (Moran's I).
diagnose( object, W = NULL, truth = NULL, rse_threshold = 25, alpha_level = 0.05 )diagnose( object, W = NULL, truth = NULL, rse_threshold = 25, alpha_level = 0.05 )
object |
A fitted model object of class |
W |
Optional spatial proximity or adjacency matrix of dimension |
truth |
Optional numeric vector containing true parameter values |
rse_threshold |
Numeric. Threshold for reliable Relative Standard Error (default is 25%). |
alpha_level |
Numeric. Significance level for hypothesis tests (default is 0.05). |
Goodness of fit. over the
sampled domains is compared with (Brown et al., 2001); only large values indicate
that the model estimates differ from the direct estimates more than their uncertainty allows, so
the p-value is upper-tailed (as in emdi). The statistic ignores the positive correlation
between and , so it is conservative: under a correct model
is typically well below its degrees of freedom.
Bias regression. The OLS fit is reported
without a formal test of : for shrinkage estimators such as the EBLUP
the slope exceeds 1 even when the model is correct (about for the part of the
variation not explained by the covariates), so that test would reject correct models. Inspect
the regression (and autoplot(x, type = "calibration")) for systematic deviations instead.
Moran's I on the residuals of the sampled domains uses the
randomisation variance of Cliff and Ord (1981), two-sided.
An object of class c("fastsae_diagnose", "list") containing:
Basic model characteristics (model name, sample size, unsampled count).
Summary of direct vs SAE RSE, proportion of areas with RSE < threshold, and MSE reduction ratios.
Brown et al. (2001) diagnostics: bias_regression (descriptive OLS
fit of the direct estimates on the model estimates, no test; see Details) and
goodness_of_fit (the statistic with its upper-tail p-value).
Moran's I test for spatial autocorrelation in model residuals (if W is available).
For Bayesian fits: DIC, WAIC, marginal log-likelihood and, when they are available per domain, CPO summaries and a Kolmogorov-Smirnov test of the PIT values.
Mean relative bias, mean absolute relative error, relative RMSE across
domains, and coverage rate (if truth is supplied).
Data frame combining direct estimates, SAE predictions, MSE, RSE, and residuals for diagnostics.
Overall assessment summary string.
Brown, G., Chambers, R., Heady, P., & Heasman, D. (2001). Evaluation of small area estimation methods: An application to the British Labour Force Survey. ONS Internal Report.
Rao, J. N. K., & Molina, I. (2015). Small Area Estimation (2nd ed.). John Wiley & Sons.
Cliff, A. D., & Ord, J. K. (1981). Spatial Processes: Models & Applications. Pion London.
library(fastsae) data(mys) data(mys_proxmat) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, data = mys, vardir = ~vardir, domain = ~area) diag_fh <- diagnose(fit_fh) print(diag_fh) # 2. Fit Spatial HB model (requires INLA) if (requireNamespace("INLA", quietly = TRUE)) { fit_hb <- hb_area(y ~ x1 + x2, data = mys, vardir = "vardir") diag_hb <- diagnose(fit_hb) print(diag_hb) }library(fastsae) data(mys) data(mys_proxmat) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, data = mys, vardir = ~vardir, domain = ~area) diag_fh <- diagnose(fit_fh) print(diag_fh) # 2. Fit Spatial HB model (requires INLA) if (requireNamespace("INLA", quietly = TRUE)) { fit_hb <- hb_area(y ~ x1 + x2, data = mys, vardir = "vardir") diag_hb <- diagnose(fit_hb) print(diag_hb) }
This function estimates small area means or totals using the unit-level model proposed by Battese, Harter, and Fuller (1988), which combines survey data (sample units) and auxiliary population information.
eblup_bhf( formula, unit_data, Xpop, domain_var, popsize_var, method = c("REML", "ML"), popnmean_xpop = NULL, B = 100, compute_mse = FALSE, n_threads = 1, seed = -1, print_result = TRUE )eblup_bhf( formula, unit_data, Xpop, domain_var, popsize_var, method = c("REML", "ML"), popnmean_xpop = NULL, B = 100, compute_mse = FALSE, n_threads = 1, seed = -1, print_result = TRUE )
formula |
An object of class 'formula' describing the model. |
unit_data |
A 'data.frame' containing the unit-level survey data. |
Xpop |
A 'data.frame' containing auxiliary variables and domain info. |
domain_var |
A character string giving the column name for domain identifier. |
popsize_var |
A character string for population size variable. |
method |
Fitting method: "REML" (default) or "ML". |
popnmean_xpop |
Population mean of auxiliary variables per domain. |
B |
Number of bootstrap replicates for MSE (if compute_mse = TRUE). |
compute_mse |
If TRUE, compute bootstrap MSE. |
n_threads |
Number of OpenMP threads for the bootstrap MSE. Results depend on
|
seed |
Random seed for reproducibility. |
print_result |
Print results (default TRUE). |
The nested error model is fitted by
REML or ML in compiled code. With ,
and are profiled out, so the fit is a
one-dimensional maximisation over (including the boundary
); each evaluation uses only within-domain cross-products
and domain means. The estimates are those of lme4::lmer and
sae::eblupBHF up to the optimiser tolerance of those packages. The
standard errors in estcoef are from .
The bootstrap MSE refits the model in each replicate with the same code and
runs replicates in parallel (n_threads); random draws are generated
sequentially from R's RNG, so a given seed gives the same result for
any number of threads.
List containing EBLUP estimates, fit, and optionally MSE. The
fit element holds the variance components, beta, the
predicted random effects and the unit-level conditional residuals.
Battese, G. E., Harter, R. M., and Fuller, W. A. (1988). An error-components model for prediction of county crop areas using survey and satellite data. *Journal of the American Statistical Association*, 83(401), 28-36.
library(dplyr) df_meanpop <- cornsoybeanmeans |> rename(CornPix = MeanCornPixPerSeg, SoyBeansPix = MeanSoyBeansPixPerSeg) df_cornsoybean <- cornsoybean |> rename(CountyIndex = County) res <- eblup_bhf( formula = CornHec ~ CornPix + SoyBeansPix, Xpop = df_meanpop, unit_data = df_cornsoybean, domain_var = "CountyIndex", popsize_var = "PopnSegments" )library(dplyr) df_meanpop <- cornsoybeanmeans |> rename(CornPix = MeanCornPixPerSeg, SoyBeansPix = MeanSoyBeansPixPerSeg) df_cornsoybean <- cornsoybean |> rename(CountyIndex = County) res <- eblup_bhf( formula = CornHec ~ CornPix + SoyBeansPix, Xpop = df_meanpop, unit_data = df_cornsoybean, domain_var = "CountyIndex", popsize_var = "PopnSegments" )
This function gives the Empirical Best Linear Unbiased Prediction (EBLUP) or Empirical Best (EB) predictor under normality based on a Fay-Herriot model.
eblup_fh( formula, vardir, domain = NULL, data, method = c("REML", "ML"), transform = c("none", "log"), maxiter = 100, precision = 1e-04, print_result = TRUE, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL )eblup_fh( formula, vardir, domain = NULL, data, method = c("REML", "ML"), transform = c("none", "log"), maxiter = 100, precision = 1e-04, print_result = TRUE, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL )
formula |
an object of class formula that contains a description of the model to be fitted. |
vardir |
vector or column names from data that contain variance sampling from the direct estimator. |
domain |
vector, column name or one-sided formula referencing a domain names column
in |
data |
a data frame or a data frame extension (e.g. a tibble). |
method |
Fitting method can be chosen between 'ML' and 'REML'. |
transform |
Character string specifying data transformation for the response:
|
maxiter |
maximum number of iterations allowed in the Fisher-scoring algorithm. |
precision |
convergence tolerance limit for the Fisher-scoring algorithm. |
print_result |
print coefficient or not, default value is TRUE. |
self_benchmark |
Logical. If |
benchmark_weight |
Optional vector, column name, or one-sided formula referencing the domain
benchmarking weights in |
benchmark_target |
Optional numeric scalar or named vector specifying fixed aggregate
benchmark target(s). If |
benchmark_group |
Optional vector, column name, or one-sided formula referencing the
grouping / stratum column in |
The model has a form that is response ~ auxiliary variables. where numeric type response variables can contain NA. When the response variable contains NA it will be estimated with synthetic estimator.
The function returns a list with the following objects:
estcoef a data frame with the estimated model coefficients,
random_effect_var estimated random effect variance,
goodness vector containing several goodness-of-fit measures,
df_eblup a data frame that contains y, eblup, random_effect, vardir, mse, and rse.
y variable response
eblup estimated results for each area
random_effect random effect for each area
vardir variance sampling from the direct estimator for each area
mse Mean Square Error
rse Relative Standart Error (%) self_benchmark logical indicating whether self-benchmarking was active, benchmark_summary summary table of benchmark calibration (if self-benchmarking).
Rao, J. N., & Molina, I. (2015). Small area estimation. John Wiley & Sons.
Rao, J. N. K., & Molina, I. (2015). Small area estimation. John Wiley & Sons.
Slud, E. V., & Maiti, T. (2006). Small-area estimation via Fay-Herriot models with logit and log transformations. Communications in Statistics - Theory and Methods, 35(10), 1957-1971.
Wang, J., Fuller, W. A., and Qu, Y. (2008). Small area estimation under a restriction. Survey Methodology, 34(1), 29-36.
library(fastsae) # Standard Fay-Herriot model m1 <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir" ) # Log-Fay-Herriot with Slud-Maiti bias correction m_log <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", transform = "log" ) # Self-benchmarking Fay-Herriot model m1_bench <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", self_benchmark = TRUE, benchmark_weight = "n" )library(fastsae) # Standard Fay-Herriot model m1 <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir" ) # Log-Fay-Herriot with Slud-Maiti bias correction m_log <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", transform = "log" ) # Self-benchmarking Fay-Herriot model m1_bench <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", self_benchmark = TRUE, benchmark_weight = "n" )
This function gives the Spatial Empirical Best Linear Unbiased Prediction (EBLUP) or Empirical Best (EB) predictor under normality based on a Fay-Herriot model.
eblup_sfh( formula, vardir, domain = NULL, data, method = c("REML", "ML"), mse_method = c("analytical", "pbmse", "npbmse"), W = NULL, B = 100, n_threads = 1, seed = -1, maxiter = 100, precision = 1e-04, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )eblup_sfh( formula, vardir, domain = NULL, data, method = c("REML", "ML"), mse_method = c("analytical", "pbmse", "npbmse"), W = NULL, B = 100, n_threads = 1, seed = -1, maxiter = 100, precision = 1e-04, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )
formula |
an object of class formula that contains a description of the model to be fitted. The variables included in the formula must be contained in the data. |
vardir |
vector or column names from data that contain variance sampling from the direct estimator for each area. |
domain |
vector, column name or one-sided formula referencing a domain names column
in |
data |
a data frame or a data frame extension (e.g. a tibble). |
method |
Fitting method can be chosen between 'ML' and 'REML'. |
mse_method |
a character string determining the estimation method of the MSE.
Methods that can be chosen: "analytical", "pbmse", or "npbmse".
When there are unsampled domains, "pbmse"/"npbmse" bootstrap MSE is only defined for the
sampled domains; unsampled domains automatically get a full-spatial synthetic (kriging)
prediction and analytical MSE merged into the result regardless of |
W |
A square matrix with dimension equal to the TOTAL number of domains in |
B |
Number of bootstrap replications when mse_method = "pbmse" or "npbmse". |
n_threads |
Number of threads used in parallel computation (default 1). Values less than or equal to 0 use all available cores. |
seed |
Integer seed for bootstrap resampling. A value of -1 leaves the current R RNG state unchanged. |
maxiter |
maximum number of iterations allowed in the Fisher-scoring algorithm. Default is 100 iterations. |
precision |
convergence tolerance limit for the Fisher-scoring algorithm. Default value is 0.0001. |
self_benchmark |
Logical. If |
benchmark_weight |
Optional vector, column name, or one-sided formula referencing the domain
benchmarking weights in |
benchmark_target |
Optional numeric scalar or named vector specifying fixed aggregate
benchmark target(s). If |
benchmark_group |
Optional vector, column name, or one-sided formula referencing the
grouping / stratum column in |
print_result |
print coefficient or not, default value is TRUE. |
The model has a form that is response ~ auxiliary variables.
where numeric type response variables can contain NA.
When the response variable contains NA, that domain is treated as unsampled: it is
predicted with a full-spatial synthetic (kriging) estimator that borrows strength from
sampled neighbors via W. The SAR process is defined on all domains of W, so the
sampled domains have covariance with
.
Analytical MSE. Sampled domains: (Singh et al., 2005;
as sae::mseSFH), minus for ML. Unsampled domains:
(minus
for ML), with from the exact derivative of the
kriging predictor; for sampled domains this second-order form agrees, up to o(1/m), with
. The inverse information used for and
is the one of the fitting method: REML information for REML and ML
information for ML. (sae::mseSFH uses the REML information also for ML; the two
agree asymptotically, but with few domains, or with
, the REML choice can make the ML bias term explode. Hence, for
method = "ML", the MSE differs from sae::mseSFH; REML results agree.)
When lies on the boundary (, or reported as
), the Prasad-Rao expansion in is not valid and can explode, so
is treated as fixed: only the block of the information is
inverted, which removes the terms from , and
(the standard error of is then NA). In this case the
MSE differs from sae::mseSFH, which keeps those terms.
If the classical (sae-compatible) Fisher scoring fails, or converges to a negative
(which sae::eblupSFH truncates to 0 without re-estimating
), the (RE)ML likelihood is maximised under the constraints
, . A lower-bound estimate
is reported as (as sae) only when is
non-singular (not for bipartite graphs such as a rook grid).
Computation. No inverse is formed: with
and
( selects the sampled domains), ,
and the remaining terms follow from Cholesky
solves with and . These are sparse for a sparse W (contiguity or
k-nearest-neighbour weights), which makes models with a few thousand domains feasible;
a dense W (e.g. inverse-distance weights) uses dense factorisations.
The function returns a list with the following objects:
estcoef a data frame with the estimated model coefficients in the first column (beta),
their asymptotic standard errors in the second column (std.error),
the t-statistics in the third column (tvalue) and the p-values of the significance of each coefficient
in last column (pvalue) random_effect_var estimated random effect variance rho estimated spatial autocorrelation parameter estvarcomp a data frame with parameter, estimate, and std.error goodness vector containing several goodness-of-fit measures: loglikelihood, AIC, and BIC df_eblup a data frame that contains the following columns:
y variable response
eblup estimated results for each area
random_effect random effect for each area
vardir variance sampling from the direct estimator for each area
mse Mean Square Error
rse Relative Standart Error (%)
mse_pb or mse_npb Parametric / Non Parametric bootstrap MSE
mse_pbbc or mse_npbbc Bias Corrected Parametric / Non Parametric bootstrap MSE
Rao, J. N., & Molina, I. (2015). Small area estimation. John Wiley & Sons.
library(fastsae) # Spatial Fay-Herriot model m1 <- eblup_sfh( y ~ x1 + x2 + x3, data = mys, vardir = ~vardir, W = mys_proxmat ) # Spatial Fay-Herriot model with Parametric Bootstrap MSE m2 <- eblup_sfh( y ~ x1 + x2 + x3, data = mys, vardir = ~vardir, mse_method = "pbmse", B = 50, W = mys_proxmat )library(fastsae) # Spatial Fay-Herriot model m1 <- eblup_sfh( y ~ x1 + x2 + x3, data = mys, vardir = ~vardir, W = mys_proxmat ) # Spatial Fay-Herriot model with Parametric Bootstrap MSE m2 <- eblup_sfh( y ~ x1 + x2 + x3, data = mys, vardir = ~vardir, mse_method = "pbmse", B = 50, W = mys_proxmat )
This function gives the Spatio-Temporal Empirical Best Linear
Unbiased Prediction (EBLUP) under normality based on a spatio-temporal
Fay-Herriot model. It reimplements the same Fisher-scoring algorithm as
eblupSTFH() (package sae, Marhuenda, Molina & Morales 2013),
but the estimation loop runs in compiled C++/Armadillo, making it substantially faster and more memory-efficient than the original
R implementation – especially for a large number of domains/time periods.
eblup_stfh( formula, vardir, data, domain, time, W, model = c("ST", "S"), maxiter = 100, precision = 1e-04, sigma21_start = NULL, rho1_start = 0.5, sigma22_start = NULL, rho2_start = 0.5, compute_mse = FALSE, mse_type = c("analytical", "bootstrap"), B = 100, n_threads = 1, seed = -1, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )eblup_stfh( formula, vardir, data, domain, time, W, model = c("ST", "S"), maxiter = 100, precision = 1e-04, sigma21_start = NULL, rho1_start = 0.5, sigma22_start = NULL, rho2_start = 0.5, compute_mse = FALSE, mse_type = c("analytical", "bootstrap"), B = 100, n_threads = 1, seed = -1, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )
formula |
an object of class formula describing the model to fit
(response ~ auxiliary variables). Variables must be present in |
vardir |
vector, column name or one-sided formula referencing a column
in |
data |
a data frame (or extension) with one row per domain and time period
( |
domain |
vector, column name or one-sided formula referencing a domain names column
in |
time |
vector, column name, or one-sided formula referencing a time names column
in |
W |
a square proximity/spatial weights matrix of dimension
|
model |
character, either |
maxiter |
maximum number of Fisher-scoring iterations. Default 100. |
precision |
convergence tolerance for the Fisher-scoring algorithm.
Default |
sigma21_start, rho1_start, sigma22_start, rho2_start
|
starting values for
the variance/autocorrelation components. Defaults mirror |
compute_mse |
logical, if |
mse_type |
character, method for MSE estimation: |
B |
number of bootstrap replicates for MSE computation. Only used when
|
n_threads |
number of threads for parallel bootstrap MSE computation.
Use |
seed |
random seed for bootstrap. Use |
self_benchmark |
Logical. If |
benchmark_weight |
Optional vector, column name, or one-sided formula referencing the domain
benchmarking weights in |
benchmark_target |
Optional numeric scalar or named vector specifying fixed aggregate
benchmark target(s). If |
benchmark_group |
Optional vector, column name, or one-sided formula referencing the
grouping / stratum column in |
print_result |
print the estimated coefficients or not. Default |
Unsampled domains and missing periods. Cells whose response is NA
(a domain without a sample in some period, or in every period) are not dropped. The
model is defined on the full grid: the SAR effect lives on
all domains of W and the AR(1) effect on all periods.
The variance components are estimated by REML from the sampled cells, i.e. from the
marginal likelihood with the missing cells integrated out (missing at random), and every
cell gets the best linear unbiased predictor of
given the sampled data (Saei and Chambers, 2005; Benedetti et al., 2024 for the
spatial effect):
with the covariance between the cell and the sampled direct estimates.
A missing period of a sampled domain borrows from the other periods of the domain (AR(1))
and from the neighbours (SAR); a domain that is never sampled is predicted from its
neighbours only (spatial kriging). With model = "S" the period effect of a missing
cell is independent of the data, so only the spatial part is borrowed.
MSE. For sampled cells the analytical MSE is
(Marhuenda et al., 2013). For the cells predicted without a direct estimate it is
, where and are the MSE of the predictor with known
variance components and comes from the exact derivative of the predictor in those
components (g4 is 0 for these cells). The further second-order correction of the
plug-in is not applied: it is numerically unstable when approaches
or a variance component is weakly identified, while in simulations
has a relative bias of a few percent and close to nominal coverage
for these cells. The parametric bootstrap generates the
random effects on the full grid and the sampling errors on the sampled cells, re-estimates
the model on the sampled cells and predicts every cell, so it covers both kinds of cells.
The auxiliary variables must be known for every cell, since they enter the prediction.
Self-benchmarking calibrates the weighted aggregate of the sampled cells of each group.
A list with the same structure as seblup_area(), with additional
estvarcomp for spatio-temporal variance/autocorrelation components:
estcoefdata frame with beta, std.error, tvalue, pvalue.
estvarcompdata frame with estimate, std.error for sigma21, rho1, sigma22, rho2.
goodnessvector with loglike, AIC, BIC.
df_eblupdata frame with domain, time, y, eblup, vardir, mse, rse,
random_effect_u1, random_effect_u2 and sampled (FALSE for the cells
predicted without a direct estimate).
When compute_mse = FALSE, mse and rse are NA.
modelmodel type ("ST" or "S").
convergencelogical, whether the algorithm converged.
n_iternumber of iterations.
Bnumber of bootstrap replicates (only when compute_mse = TRUE and mse_type = "bootstrap").
Marhuenda, Y., Molina, I., & Morales, D. (2013). Small area estimation with spatio-temporal Fay-Herriot models. Computational Statistics & Data Analysis, 58, 308-325.
Rao, J. N., & Molina, I. (2015). Small area estimation. John Wiley & Sons.
Saei, A., & Chambers, R. (2005). Out of sample estimation for small areas using area level data. Southampton Statistical Sciences Research Institute, Methodology Working Paper M05/11.
Benedetti, R., Piersimoni, F., Pratesi, M., Salvati, N., & Suesse, T. (2024). Handling out-of-sample areas to estimate the unemployment rate at local labour market areas in Italy. International Statistical Review. doi:10.1111/insr.12596
library(fastsae) # mys_panel: 42 domains x 11 years; domains 21 and 25 are never sampled (y = NA). # They stay in the data and in W, and are predicted from their neighbours. m1 <- eblup_stfh( y ~ x1 + x2 + x3, data = mys_panel, vardir = ~vardir, domain = ~area, time = ~year, W = mys_proxmat, model = "ST" ) # Analytical MSE for every cell, sampled or not m2 <- eblup_stfh( y ~ x1 + x2 + x3, data = mys_panel, vardir = ~vardir, domain = ~area, time = ~year, W = mys_proxmat, model = "ST", compute_mse = TRUE, mse_type = "analytical" ) head(m2$df_eblup[!m2$df_eblup$sampled, ])library(fastsae) # mys_panel: 42 domains x 11 years; domains 21 and 25 are never sampled (y = NA). # They stay in the data and in W, and are predicted from their neighbours. m1 <- eblup_stfh( y ~ x1 + x2 + x3, data = mys_panel, vardir = ~vardir, domain = ~area, time = ~year, W = mys_proxmat, model = "ST" ) # Analytical MSE for every cell, sampled or not m2 <- eblup_stfh( y ~ x1 + x2 + x3, data = mys_panel, vardir = ~vardir, domain = ~area, time = ~year, W = mys_proxmat, model = "ST", compute_mse = TRUE, mse_type = "analytical" ) head(m2$df_eblup[!m2$df_eblup$sampled, ])
This function gives the Empirical Best Linear Unbiased Prediction (EBLUP)
under a two-fold Fay-Herriot model (Torabi & Rao, 2014): subareas nested within areas
with an area random effect and a subarea random effect .
eblup_twofold( formula, vardir, domain = NULL, subarea = NULL, data, method = c("REML", "ML"), mse = c("analytical", "bootstrap"), B = 200, seed = NULL, maxiter = 100, precision = 1e-04, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )eblup_twofold( formula, vardir, domain = NULL, subarea = NULL, data, method = c("REML", "ML"), mse = c("analytical", "bootstrap"), B = 200, seed = NULL, maxiter = 100, precision = 1e-04, self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, print_result = TRUE )
formula |
an object of class formula that contains a description of the model to be fitted. |
vardir |
vector or column names from data that contain variance sampling from the direct estimator. |
domain |
vector, column name or one-sided formula referencing the area identifier column
in |
subarea |
vector, column name or one-sided formula referencing the subarea identifier column
in |
data |
a data frame or a data frame extension (e.g. a tibble), one row per subarea. |
method |
Fitting method can be chosen between 'REML' and 'ML'. |
mse |
MSE estimation method: 'analytical' (Prasad-Rao g1+g2+2*g3, fast; ML adds the bias correction) or 'bootstrap' (parametric bootstrap, slower but robust). |
B |
number of parametric bootstrap replicates (only used if mse = 'bootstrap'). |
seed |
integer seed for bootstrap resampling (NULL = no seed set). |
maxiter |
maximum number of iterations allowed in the Fisher-scoring algorithm. |
precision |
convergence tolerance limit for the Fisher-scoring algorithm. |
self_benchmark |
Logical. If |
benchmark_weight |
Optional vector, column name, or one-sided formula referencing the domain
benchmarking weights in |
benchmark_target |
Optional numeric scalar or named vector specifying fixed aggregate
benchmark target(s). If |
benchmark_group |
Optional vector, column name, or one-sided formula referencing the
grouping / stratum column in |
print_result |
print coefficient or not, default value is TRUE. |
The model has a form that is response ~ auxiliary variables, with one row per subarea. When the response contains NA the subarea is treated as non-sampled and predicted with the synthetic estimator. MSE is estimated either analytically (Prasad-Rao g1+g2+2*g3 for REML, minus the ML bias term b'grad(g1) for ML, with an exact matrix derivation for g3) or by parametric bootstrap.
The function returns a list with the following objects:
estcoef a data frame with the estimated model coefficients,
random_effect_var named vector with the estimated area (sigma2_v) and
subarea (sigma2_u) variances (paper notation),
goodness vector containing several goodness-of-fit measures,
df_eblup a data frame that contains domain, subarea, y, eblup, vardir,
random_effect_area, random_effect_subarea, mse, and rse.
Torabi, M., & Rao, J. N. K. (2014). On small area estimation under a sub-area level model. Journal of Multivariate Analysis, 127, 36–55.
Rao, J. N. K., & Molina, I. (2015). Small Area Estimation. John Wiley & Sons.
library(fastsae) # Two-fold Fay-Herriot model (simulated illustration) set.seed(1) m <- 20 dat <- do.call(rbind, lapply(1:m, function(d) { nd <- sample(2:5, 1) data.frame( area = d, subarea = paste0(d, "-", seq_len(nd)), x1 = rnorm(nd), y = NA_real_, vardir = runif(nd, 0.2, 1) ) })) dat$y <- 1 + dat$x1 + rnorm(m)[dat$area] + rnorm(nrow(dat), sd = 0.5) + rnorm(nrow(dat), sd = sqrt(dat$vardir)) m1 <- eblup_twofold(y ~ x1, vardir = "vardir", domain = "area", subarea = "subarea", data = dat)library(fastsae) # Two-fold Fay-Herriot model (simulated illustration) set.seed(1) m <- 20 dat <- do.call(rbind, lapply(1:m, function(d) { nd <- sample(2:5, 1) data.frame( area = d, subarea = paste0(d, "-", seq_len(nd)), x1 = rnorm(nd), y = NA_real_, vardir = runif(nd, 0.2, 1) ) })) dat$y <- 1 + dat$x1 + rnorm(m)[dat$area] + rnorm(nrow(dat), sd = 0.5) + rnorm(nrow(dat), sd = sqrt(dat$vardir)) m1 <- eblup_twofold(y ~ x1, vardir = "vardir", domain = "area", subarea = "subarea", data = dat)
Exports comprehensive estimation tables and model summaries to multi-sheet
Excel workbooks (.xlsx) or comma-separated files (.csv). Formatted
to meet official statistics dissemination standards.
The generated Excel workbook contains up to four sheets:
Estimates: Domain IDs, Direct survey estimates, SAE model predictions, Standard Errors (SE), MSE, RSE (%), 95% confidence / credible intervals, and official Reliability Flags.
Model_Summary: Model formula, method, convergence status, regression
coefficients (, SE, p-values), variance components (,
spatial , temporal , ), and goodness-of-fit metrics.
Benchmarked (Optional): Pre- vs post-calibration values, adjustments, and percentage shifts when benchmarking calibration is applied.
Benchmarked_Groups (Optional): the group-level (stage 1) calibration of a hierarchical benchmark.
With a .csv file, the estimates are written to file and the model summary to
<file>_summary.csv; the benchmark sheets are only written to Excel workbooks.
export_sae( object, file, benchmark = NULL, thresholds = c(25, 50), overwrite = TRUE, ... )export_sae( object, file, benchmark = NULL, thresholds = c(25, 50), overwrite = TRUE, ... )
object |
A fitted |
file |
Character string specifying the target file path (must end with |
benchmark |
Optional |
thresholds |
Numeric vector of length 2 with the RSE (%) cut-offs of the reliability flags
(see |
overwrite |
Logical indicating whether to overwrite an existing file. Default is |
... |
Additional arguments. |
Invisibly returns a named list of data frames corresponding to the exported sheets.
library(fastsae) data(mys) fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) tmp_file <- tempfile(fileext = ".xlsx") export_sae(fit_fh, file = tmp_file) unlink(tmp_file)library(fastsae) data(mys) fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) tmp_file <- tempfile(fileext = ".xlsx") export_sae(fit_fh, file = tmp_file) unlink(tmp_file)
Extract fitted values (EBLUP or HB) from a fastsae object
## S3 method for class 'fastsae' fitted(object, ...)## S3 method for class 'fastsae' fitted(object, ...)
object |
An object of class |
... |
Additional arguments. |
Vector of fitted estimates.
Fits Generalized Variance Function (GVF) models to smooth unstable
direct sampling variance estimates () in Small Area Estimation.
Supports log-linear regression (Wolter, 2007), Gamma generalized linear models
(GLM with log link), and CV power models.
gvf_smooth( vardir, y = NULL, n = NULL, method = c("log_linear", "gamma_glm", "cv_power"), data = NULL, formula = NULL, bias_correction = TRUE )gvf_smooth( vardir, y = NULL, n = NULL, method = c("log_linear", "gamma_glm", "cv_power"), data = NULL, formula = NULL, bias_correction = TRUE )
vardir |
vector, column name, or one-sided formula referencing the direct sampling variances in |
y |
optional vector, column name, or one-sided formula referencing the direct survey estimates. |
n |
optional vector, column name, or one-sided formula referencing domain sample sizes. |
method |
character string specifying the GVF smoothing model:
Default is |
data |
optional data frame containing the variables. |
formula |
optional user-supplied formula overriding the default model specification. |
bias_correction |
logical. For |
An object of class "gvf_smooth" and "fastsae_gvf", containing:
smooth_vardirnumeric vector of smoothed sampling variances .
vardiroriginal raw sampling variances.
fitted_modelthe fitted lm or glm model object.
methodmethod used.
r_squaredcoefficient of determination (or pseudo- for GLM).
dfdata frame with raw vardir, smooth_vardir, and covariates.
callthe matched function call.
Wolter, K. M. (2007). Introduction to Variance Estimation (2nd ed.). Springer.
Rao, J. N. K., & Molina, I. (2015). Small Area Estimation (2nd ed.). John Wiley & Sons.
Rivest, L. P., & Belmonte, E. (2000). A conditional mean squared error of small area estimators. Survey Methodology, 26(1), 67-78.
library(fastsae) # Smooth direct variances using direct estimates y and sample size n gvf_res <- gvf_smooth( vardir = "vardir", y = "y", n = "n", data = mys, method = "log_linear" ) # Inspect summary summary(gvf_res) # Use smoothed variances directly in Fay-Herriot model fit_fh <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = gvf_res$smooth_vardir )library(fastsae) # Smooth direct variances using direct estimates y and sample size n gvf_res <- gvf_smooth( vardir = "vardir", y = "y", n = "n", data = mys, method = "log_linear" ) # Inspect summary summary(gvf_res) # Use smoothed variances directly in Fay-Herriot model fit_fh <- eblup_fh( y ~ x1 + x2 + x3, data = mys, vardir = gvf_res$smooth_vardir )
Estimates small area parameters using area-level Hierarchical Bayesian models
under various distributions (Gaussian, Binomial, Poisson, Negative Binomial, Beta, Gamma)
and spatial random effect structures (non-spatial, BYM2, BYM, Besag/ICAR, Leroux).
Two estimation engines are available through engine:
inla_engine() (default, or "inla"): Integrated Nested
Laplace Approximations (INLA; Rue et al., 2009).
jax_engine() (or "jax"): full MCMC with the No-U-Turn sampler
of 'NumPyro' (Phan et al., 2019) on 'JAX', on the CPU or an NVIDIA GPU. Needs Python
with jax and numpyro through reticulate; see
setup_numpyro_env.
The engine constructors hold all engine settings (priors, approximation strategy and
further INLA::inla() arguments for INLA; MCMC length, device and coefficient prior
for JAX), so hb_area() itself only describes the model.
hb_area( formula, data, domain = NULL, time = NULL, family = c("gaussian", "binomial", "poisson", "nbinomial", "beta", "gamma"), spatial = c("none", "bym2", "bym", "besag", "generic1", "leroux", "slm"), temporal = c("none", "rw1", "rw2", "ar1", "iid"), st_interaction = c("none", "domain-specific", "separable", "type1", "type2", "type3", "type4"), W = NULL, vardir = NULL, trials = NULL, exposure = NULL, engine = "inla", self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, benchmark_method = c("posterior", "wfq"), print_result = TRUE, method = NULL, ... )hb_area( formula, data, domain = NULL, time = NULL, family = c("gaussian", "binomial", "poisson", "nbinomial", "beta", "gamma"), spatial = c("none", "bym2", "bym", "besag", "generic1", "leroux", "slm"), temporal = c("none", "rw1", "rw2", "ar1", "iid"), st_interaction = c("none", "domain-specific", "separable", "type1", "type2", "type3", "type4"), W = NULL, vardir = NULL, trials = NULL, exposure = NULL, engine = "inla", self_benchmark = FALSE, benchmark_weight = NULL, benchmark_target = NULL, benchmark_group = NULL, benchmark_method = c("posterior", "wfq"), print_result = TRUE, method = NULL, ... )
formula |
An object of class |
data |
A |
domain |
Vector, column name, or one-sided formula referencing the area/domain
identifier in |
time |
Vector, column name, or one-sided formula referencing the time period
identifier in |
family |
Character string specifying the response distribution / likelihood. Options:
|
spatial |
Character string specifying the spatial random effect structure:
|
temporal |
Character string specifying the temporal random effect structure:
|
st_interaction |
Character string specifying the spatio-temporal structure:
|
W |
Proximity or spatial adjacency matrix. Can be a square |
vardir |
Vector, column name, or formula specifying the sampling variances of the
direct estimator (for |
trials |
Vector, column name, or formula specifying sample sizes / total trials
per area (for |
exposure |
Vector, column name, or formula specifying expected counts or population
exposure offsets (for |
engine |
Estimation engine: |
self_benchmark |
Logical. If |
benchmark_weight |
Optional vector, column name, or one-sided formula referencing the domain
benchmarking weights in |
benchmark_target |
Optional numeric scalar or named vector specifying fixed aggregate
benchmark target(s). If |
benchmark_group |
Optional vector, column name, or one-sided formula referencing the
grouping / stratum column in |
benchmark_method |
How self-benchmarking is done when |
print_result |
Logical. If |
method |
Deprecated; use |
... |
Deprecated. |
An object of class c("fastsae_hb_area", "fastsae") containing:
df_hb: Data frame with domain estimates, including domain,
time (if specified), observed y, predicted hb, linear predictor linear_pred,
posterior standard error sd, mse, relative error rse (%),
95% credible interval (ci_lower, ci_upper), and random_effect.
estcoef: Data frame of estimated regression coefficients.
hyperpar: Data frame of hyperparameter posterior estimates.
random_effect_var: Estimated area random effect variance.
random_effect_var_time: Estimated temporal random effect variance (if temporal).
phi: Estimated spatial variance proportion (for BYM2) or spatial autocorrelation.
rho_time: Estimated temporal autocorrelation parameter (for AR1).
goodness: Model fit metrics (DIC, WAIC, Marginal Log-Likelihood).
family: Response family used.
spatial: Spatial model type used.
temporal: Temporal model type used.
st_interaction: Spatio-temporal interaction type used.
self_benchmark: Logical indicating whether self-benchmarking was active.
benchmark_summary: Summary table of benchmark calibration (if self-benchmarking).
fit: Raw fitted model object (inla, or the list returned by the
Python backend for the JAX engine).
engine: Name of the estimation engine ("inla" or "jax");
engine_spec holds its settings (inla_engine() or
jax_engine() object).
draws, rhat_max, device, elapsed_seconds: With the
JAX engine, the posterior draws of the area parameters (rows of df_hb
by draws), the largest split R-hat (convergence is rhat_max < 1.05), the
JAX device and the sampling time.
call: Matched function call.
Both engines return the same structure, so print, summary,
benchmark_sae, compare_sae and the other methods work
with either. Feature support:
| Feature | inla | jax |
| Families | all six | all six |
spatial |
all | all but "slm" |
temporal |
all | all but "rw2" |
st_interaction |
all | all |
| Self-benchmarking | posterior, wfq | posterior; wfq (gaussian) |
| Horseshoe prior, Student-t errors | -- | yes |
The "jax" engine uses weakly informative priors (half-normal standard deviations,
uniform spatial mixing / autocorrelation parameters) instead of the PC priors of INLA, so its
estimates differ slightly. For family = "gamma" it estimates a common shape and does
not use vardir.
Rao, J. N. K., and Molina, I. (2015). Small Area Estimation. John Wiley & Sons.
Wang, J., Fuller, W. A., and Qu, Y. (2008). Small area estimation under a restriction. Survey Methodology, 34(1), 29-36.
Riebler, A., Sørbye, S. H., Simpson, D., and Rue, H. (2016). An intuitive Bayesian spatial model for disease mapping that accounts for scaling. Statistical Methods in Medical Research, 25(4), 1145-1165.
Marhuenda, Y., Molina, I., and Morales, D. (2013). Small area estimation with spatio-temporal Fay-Herriot models. Computational Statistics & Data Analysis, 58, 308-325.
De Nicolò, S., and Gardini, A. (2024). The R Package tipsae: Tools for Mapping Proportions and Indicators on the Unit Interval. Journal of Statistical Software, 108(1), 1-36.
Phan, D., Pradhan, N., and Jankowiak, M. (2019). Composable effects for flexible and accelerated probabilistic programming in NumPyro. arXiv:1912.11554.
Piironen, J., and Vehtari, A. (2017). Sparsity information and regularization in the horseshoe and other shrinkage priors. Electronic Journal of Statistics, 11(2), 5018-5051.
Rue, H., Martino, S., and Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations. Journal of the Royal Statistical Society: Series B, 71(2), 319-392.
if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) # 1. Non-spatial Gaussian Fay-Herriot with INLA m_norm <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", family = "gaussian" ) # 2. Self-benchmarking Fay-Herriot with INLA (benchmarked posterior draws) m_bench <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", self_benchmark = TRUE, benchmark_weight = "n" ) # 3. Spatial BYM2 Gaussian Fay-Herriot with INLA, faster approximation m_bym2 <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", family = "gaussian", spatial = "bym2", W = mys_proxmat, engine = inla_engine(strategy = "simplified.laplace") ) } # 4. The same Fay-Herriot model by MCMC (NumPyro NUTS on JAX) if (check_numpyro_available()) { m_jax <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", engine = jax_engine(samples = 500, chains = 2) ) }if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) # 1. Non-spatial Gaussian Fay-Herriot with INLA m_norm <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", family = "gaussian" ) # 2. Self-benchmarking Fay-Herriot with INLA (benchmarked posterior draws) m_bench <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", self_benchmark = TRUE, benchmark_weight = "n" ) # 3. Spatial BYM2 Gaussian Fay-Herriot with INLA, faster approximation m_bym2 <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", family = "gaussian", spatial = "bym2", W = mys_proxmat, engine = inla_engine(strategy = "simplified.laplace") ) } # 4. The same Fay-Herriot model by MCMC (NumPyro NUTS on JAX) if (check_numpyro_available()) { m_jax <- hb_area( y ~ x1 + x2 + x3, data = mys, vardir = "vardir", engine = jax_engine(samples = 500, chains = 2) ) }
Constructors for the engine argument of hb_area,
hb_unit and hb_twofold. Each collects the
settings of one estimation engine, so that the model functions themselves
only describe the model. Passing the string "inla" or "jax"
is the same as passing inla_engine() or jax_engine() with
their defaults.
inla_engine( strategy = c("laplace", "simplified.laplace", "gaussian"), link = NULL, scale_model = TRUE, prior_prec = NULL, prior_phi = NULL, prior_rho = NULL, prior_prec_time = NULL, prior_rho_time = NULL, prior_prec_subarea = NULL, draws = NULL, seed = 0L, ... ) jax_engine( warmup = 500, samples = 1000, chains = 2, device = c("auto", "cpu", "cuda", "metal"), seed = 42, prior_beta = c("normal", "horseshoe"), robust = FALSE, keep_draws = TRUE, progress = interactive() ) ## S3 method for class 'fastsae_engine' print(x, ...)inla_engine( strategy = c("laplace", "simplified.laplace", "gaussian"), link = NULL, scale_model = TRUE, prior_prec = NULL, prior_phi = NULL, prior_rho = NULL, prior_prec_time = NULL, prior_rho_time = NULL, prior_prec_subarea = NULL, draws = NULL, seed = 0L, ... ) jax_engine( warmup = 500, samples = 1000, chains = 2, device = c("auto", "cpu", "cuda", "metal"), seed = 42, prior_beta = c("normal", "horseshoe"), robust = FALSE, keep_draws = TRUE, progress = interactive() ) ## S3 method for class 'fastsae_engine' print(x, ...)
strategy |
INLA approximation strategy: |
link |
Link function for the likelihood ( |
scale_model |
Logical; scale the intrinsic GMRF models (besag, bym,
rw1, rw2) to a generalized variance of 1. Default |
prior_prec |
Prior for the precision of the area (domain) random
effect. |
prior_phi |
Prior for the mixing parameter of |
prior_rho |
Prior for the spatial correlation of
|
prior_prec_time |
Prior for the precision of the temporal random
effect ( |
prior_rho_time |
Prior for the autocorrelation of
|
prior_prec_subarea |
Prior for the precision of the subarea random
effect ( |
draws |
Number of posterior draws from
|
seed |
Random seed of the sampler. Default 42. |
... |
Further arguments passed to |
warmup |
Number of warmup (adaptation) iterations per chain. Default 500. |
samples |
Number of posterior draws kept per chain. Default 1000. |
chains |
Number of MCMC chains. Default 2. With more than one chain,
the fit reports the largest split R-hat and |
device |
|
prior_beta |
Prior for the regression coefficients: |
robust |
Logical; Student-t sampling errors instead of normal
(Gaussian family only). Default |
keep_draws |
Logical; keep the posterior draws of the area parameters
in |
progress |
Logical; show NumPyro's progress bar. Default
|
x |
A |
An object of class "fastsae_engine".
inla_engine() fits the model by integrated nested Laplace
approximation (INLA); it is available for all HB models. Priors are
given in INLA syntax. A prior or setting left at NULL takes the
default of the model function; a setting the model does not use (such as
prior_rho_time in hb_unit()) is ignored with a warning.
jax_engine() fits the model by MCMC (NumPyro's No-U-Turn sampler on
JAX, Phan et al. 2019) on CPU, CUDA GPU or Apple Metal, through
reticulate. It needs Python with jax and numpyro; see
setup_numpyro_env and check_numpyro_available.
The fixed effects get a normal or a regularized horseshoe prior (Piironen
and Vehtari 2017), and the variance components half-normal priors.
spatial = "slm" and temporal = "rw2" are not available.
jax_engine() is available for hb_area() only.
Phan, D., Pradhan, N. and Jankowiak, M. (2019). Composable effects for flexible and accelerated probabilistic programming in NumPyro. arXiv:1912.11554.
Piironen, J. and Vehtari, A. (2017). Sparsity information and regularization in the horseshoe and other shrinkage priors. Electronic Journal of Statistics, 11(2), 5018–5051.
inla_engine(strategy = "simplified.laplace") jax_engine(samples = 2000, chains = 4, device = "cuda")inla_engine(strategy = "simplified.laplace") jax_engine(samples = 2000, chains = 4, device = "cuda")
Estimates small area parameters under a two-fold sub-area level model
(Torabi & Rao, 2014 Bayesian hierarchical framework) using Integrated Nested
Laplace Approximations (INLA). The model accounts for nested random effects
at both the primary area level () and the nested sub-area level (),
supporting Gaussian, Binomial (logistic), and Poisson responses, with optional
spatial correlation structures (BYM2, Besag) across areas and aggregate area-level
estimation.
hb_twofold( formula, vardir = NULL, domain, subarea = NULL, data, family = c("gaussian", "binomial", "poisson"), spatial = c("none", "bym2", "besag"), W = NULL, weight = NULL, trials = NULL, exposure = NULL, engine = "inla", compute_area = TRUE, print_result = TRUE, ... )hb_twofold( formula, vardir = NULL, domain, subarea = NULL, data, family = c("gaussian", "binomial", "poisson"), spatial = c("none", "bym2", "besag"), W = NULL, weight = NULL, trials = NULL, exposure = NULL, engine = "inla", compute_area = TRUE, print_result = TRUE, ... )
formula |
An object of class |
vardir |
Character string or vector specifying direct sampling variances
( |
domain |
Character string, column name, or vector referencing the primary area identifier
in |
subarea |
Optional character string, column name, or vector referencing the sub-area identifier
in |
data |
A |
family |
Character string specifying the response likelihood. Options:
|
spatial |
Character string specifying the spatial structure across primary areas:
|
W |
Proximity or spatial adjacency matrix across unique primary areas. Can be a square |
weight |
Optional character string or numeric vector specifying sub-area population weights
( |
trials |
Optional character string or vector specifying total number of trials per sub-area.
Required when |
exposure |
Optional character string or vector specifying expected baseline exposures per sub-area.
Required when |
engine |
Estimation engine: |
compute_area |
Logical. If |
print_result |
Logical. If |
... |
Deprecated. |
An object of class c("fastsae_hb_twofold", "fastsae_hb", "fastsae") containing:
df_hb: Data frame with sub-area level estimates:
domain: Primary area identifier.
subarea: Sub-area identifier.
y: Direct estimate / observed response (NA for unsampled).
hb: Posterior mean estimate of sub-area mean.
linear_pred: Posterior mean of linear predictor.
vardir: Direct sampling variance (for Gaussian).
sd: Posterior standard deviation (standard error).
mse: Posterior Mean Squared Error ().
rse: Relative Standard Error (%).
ci_lower: 2.5% quantile of posterior credible interval.
ci_upper: 97.5% quantile of posterior credible interval.
random_effect_area: Posterior mean of area random effect ().
random_effect_subarea: Posterior mean of sub-area random effect ().
df_area: Data frame with aggregate primary area-level estimates:
domain: Primary area identifier.
hb_area: Aggregate area mean estimate.
sd_area: Posterior standard error of area estimate.
mse_area: Posterior Mean Squared Error of area estimate.
rse_area: Relative Standard Error of area estimate (%).
ci_lower_area: 2.5% quantile of area credible interval.
ci_upper_area: 97.5% quantile of area credible interval.
n_subareas: Number of sub-areas in the area.
df_subarea: Alias pointing to df_hb.
estcoef: Data frame of estimated regression coefficients (, standard error, z-value, p-value, credible intervals).
hyperpar: Data frame of hyperparameter posterior estimates.
random_effect_var: Named vector with area (sigma2_v) and sub-area (sigma2_u) variances.
phi: Estimated spatial variance proportion (for BYM2).
goodness: Model fit metrics (DIC, WAIC, Marginal Log-Likelihood).
family: Response family used.
spatial: Spatial model type used.
model: Label of model ("HB-TWOFOLD").
method: Description of method.
convergence: Logical indicating convergence.
level: "subarea".
fit: Raw fitted INLA model object.
engine, engine_spec: Engine name ("inla") and its settings.
call: Matched function call.
Torabi, M., & Rao, J. N. K. (2014). On small area estimation under a sub-area level model. Journal of Multivariate Analysis, 127, 36-55.
Rao, J. N. K., & Molina, I. (2015). Small Area Estimation (2nd ed.). John Wiley & Sons.
Riebler, A., Sørbye, S. H., Simpson, D., & Rue, H. (2016). An intuitive Bayesian spatial model for disease mapping that accounts for scaling. Statistical Methods in Medical Research, 25(4), 1145-1165.
if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) set.seed(42) m <- 10 dat <- do.call(rbind, lapply(1:m, function(d) { nd <- sample(2:4, 1) data.frame( area = d, subarea = paste0(d, "-", seq_len(nd)), x1 = rnorm(nd), vardir = runif(nd, 0.2, 0.8) ) })) dat$y <- 1 + dat$x1 + rnorm(m)[dat$area] + rnorm(nrow(dat), sd = 0.5) + rnorm(nrow(dat), sd = sqrt(dat$vardir)) fit <- hb_twofold(y ~ x1, vardir = "vardir", domain = "area", subarea = "subarea", data = dat) summary(fit) }if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) set.seed(42) m <- 10 dat <- do.call(rbind, lapply(1:m, function(d) { nd <- sample(2:4, 1) data.frame( area = d, subarea = paste0(d, "-", seq_len(nd)), x1 = rnorm(nd), vardir = runif(nd, 0.2, 0.8) ) })) dat$y <- 1 + dat$x1 + rnorm(m)[dat$area] + rnorm(nrow(dat), sd = 0.5) + rnorm(nrow(dat), sd = sqrt(dat$vardir)) fit <- hb_twofold(y ~ x1, vardir = "vardir", domain = "area", subarea = "subarea", data = dat) summary(fit) }
Estimates small area parameters using unit-level Hierarchical Bayesian models (Battese-Harter-Fuller model and generalized linear mixed models) with Integrated Nested Laplace Approximations (INLA). Supports Gaussian, Binomial (logistic regression for binary unit responses), and Poisson likelihoods, with optional spatial random effect structures (BYM2, Besag) and finite population adjustments.
hb_unit( formula, unit_data, Xpop, domain_var, popsize_var = NULL, family = c("gaussian", "binomial", "poisson"), spatial = c("none", "bym2", "besag"), W = NULL, popnmean_xpop = NULL, engine = "inla", print_result = TRUE, ... )hb_unit( formula, unit_data, Xpop, domain_var, popsize_var = NULL, family = c("gaussian", "binomial", "poisson"), spatial = c("none", "bym2", "besag"), W = NULL, popnmean_xpop = NULL, engine = "inla", print_result = TRUE, ... )
formula |
An object of class |
unit_data |
A |
Xpop |
A |
domain_var |
Character string specifying the column name for the domain identifier
in both |
popsize_var |
Optional character string specifying the column name for domain population
sizes ( |
family |
Character string specifying the response likelihood. Options:
|
spatial |
Character string specifying the spatial random effect structure across domains:
|
W |
Proximity or spatial adjacency matrix. Can be a square |
popnmean_xpop |
Optional matrix or data frame of auxiliary population means per domain.
If |
engine |
Estimation engine: |
print_result |
Logical. If |
... |
Deprecated. |
An object of class c("fastsae_hb_unit", "fastsae_hb", "fastsae") containing:
df_hb: Data frame with domain estimates, including:
domain: Domain identifier.
hb: Estimated domain mean or proportion.
linear_pred: Posterior mean of domain linear predictor.
sd: Posterior standard deviation (standard error).
mse: Posterior Mean Squared Error ().
rse: Relative Standard Error (%).
ci_lower: 2.5% quantile of posterior credible interval.
ci_upper: 97.5% quantile of posterior credible interval.
samp_size: Sample size () in the domain (0 for unsampled).
pop_size: Population size (), if popsize_var is provided.
estimated_total: Estimated domain population total (if popsize_var is provided).
sample_mean: Direct sample mean ().
random_effect: Posterior mean of domain random effect ().
estcoef: Data frame of estimated regression coefficients (posterior mean, sd, z-value, p-value, credible intervals).
hyperpar: Data frame of hyperparameter posterior estimates.
random_effect_var: Estimated domain random effect variance ().
residual_var: Estimated residual variance (, for Gaussian).
phi: Estimated spatial variance proportion (for BYM2).
goodness: Model fit metrics (DIC, WAIC, Marginal Log-Likelihood).
family: Response family used.
spatial: Spatial model type used.
unsampled_domains: Character vector of unsampled domain identifiers.
fit: Raw fitted INLA model object.
engine, engine_spec: Engine name ("inla") and its settings.
call: Matched function call.
Battese, G. E., Harter, R. M., & Fuller, W. A. (1988). An error-components model for prediction of county crop areas using survey and satellite data. Journal of the American Statistical Association, 83(401), 28-36.
Rao, J. N. K., & Molina, I. (2015). Small Area Estimation (2nd ed.). John Wiley & Sons.
Riebler, A., Sørbye, S. H., Simpson, D., & Rue, H. (2016). An intuitive Bayesian spatial model for disease mapping that accounts for scaling. Statistical Methods in Medical Research, 25(4), 1145-1165.
Rue, H., Martino, S., & Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations. Journal of the Royal Statistical Society: Series B, 71(2), 319-392.
if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) data(cornsoybean) data(cornsoybeanmeans) # Prepare auxiliary population means df_pop <- cornsoybeanmeans names(df_pop)[names(df_pop) == "MeanCornPixPerSeg"] <- "CornPix" names(df_pop)[names(df_pop) == "MeanSoyBeansPixPerSeg"] <- "SoyBeansPix" # Unit survey data df_sample <- cornsoybean names(df_sample)[names(df_sample) == "County"] <- "CountyIndex" # Fit unit-level Hierarchical Bayes model fit_hb_u <- hb_unit( formula = CornHec ~ CornPix + SoyBeansPix, unit_data = df_sample, Xpop = df_pop, domain_var = "CountyIndex", popsize_var = "PopnSegments" ) print(fit_hb_u) }if (requireNamespace("INLA", quietly = TRUE)) { library(fastsae) data(cornsoybean) data(cornsoybeanmeans) # Prepare auxiliary population means df_pop <- cornsoybeanmeans names(df_pop)[names(df_pop) == "MeanCornPixPerSeg"] <- "CornPix" names(df_pop)[names(df_pop) == "MeanSoyBeansPixPerSeg"] <- "SoyBeansPix" # Unit survey data df_sample <- cornsoybean names(df_sample)[names(df_sample) == "County"] <- "CountyIndex" # Fit unit-level Hierarchical Bayes model fit_hb_u <- hb_unit( formula = CornHec ~ CornPix + SoyBeansPix, unit_data = df_sample, Xpop = df_pop, domain_var = "CountyIndex", popsize_var = "PopnSegments" ) print(fit_hb_u) }
Provides a comprehensive, single-gateway ("satu pintu") spatial choropleth mapping
interface for Small Area Estimation models fitted with fastsae (e.g. eblup_fh,
eblup_sfh, eblup_stfh, eblup_bhf, hb_area, and benchmark_sae).
Intelligently handles:
Single Model Visualizations: Point estimates ("estimate"), Relative
Standard Error ("rse"), and 3-color official statistics reliability classification
("reliability": green for reliable, amber for use with caution, red for unreliable; cut-offs
from thresholds, see add_reliability_flags).
Direct vs Model Comparisons: Side-by-side facet maps contrasting erratic direct survey
estimates against smoothed small area model estimates ("comparison").
Two-Model Comparisons: Side-by-side maps or spatial difference maps ("difference")
contrasting two competing models (e.g. Classical FH vs Spatial FH, or FastSAE vs Stan).
Benchmarked Calibrations: Visualizing pre- vs post-benchmarked calibrations.
Smart Key Matching: Automatically detects the common domain identifier between
the model and sf_geom, with optional manual override via key.
map_sae(object, ...) ## S3 method for class 'fastsae' map_sae( object, model2 = NULL, sf_geom = NULL, key = NULL, type = c("estimate", "rse", "reliability", "comparison", "difference"), indicator = NULL, palette = NULL, thresholds = c(25, 50), facet_scales = "fixed", title = NULL, subtitle = NULL, ... ) ## S3 method for class 'fastsae_benchmark' map_sae( object, sf_geom = NULL, key = NULL, type = c("comparison", "estimate", "difference"), indicator = NULL, palette = NULL, title = NULL, subtitle = NULL, ... ) ## S3 method for class 'list' map_sae( object, sf_geom = NULL, key = NULL, type = c("comparison", "difference"), indicator = NULL, palette = NULL, title = NULL, subtitle = NULL, ... ) ## Default S3 method: map_sae( object, sf_geom = NULL, key = NULL, type = c("estimate", "rse", "reliability"), indicator = NULL, palette = NULL, thresholds = c(25, 50), title = NULL, subtitle = NULL, ... )map_sae(object, ...) ## S3 method for class 'fastsae' map_sae( object, model2 = NULL, sf_geom = NULL, key = NULL, type = c("estimate", "rse", "reliability", "comparison", "difference"), indicator = NULL, palette = NULL, thresholds = c(25, 50), facet_scales = "fixed", title = NULL, subtitle = NULL, ... ) ## S3 method for class 'fastsae_benchmark' map_sae( object, sf_geom = NULL, key = NULL, type = c("comparison", "estimate", "difference"), indicator = NULL, palette = NULL, title = NULL, subtitle = NULL, ... ) ## S3 method for class 'list' map_sae( object, sf_geom = NULL, key = NULL, type = c("comparison", "difference"), indicator = NULL, palette = NULL, title = NULL, subtitle = NULL, ... ) ## Default S3 method: map_sae( object, sf_geom = NULL, key = NULL, type = c("estimate", "rse", "reliability"), indicator = NULL, palette = NULL, thresholds = c(25, 50), title = NULL, subtitle = NULL, ... )
object |
A fitted |
... |
Additional arguments passed to |
model2 |
Optional second |
sf_geom |
Spatial polygon geometry of class |
key |
Optional character string or named vector specifying the column(s) used to match
model domain identifiers with the spatial geometry in
|
type |
Character string specifying the visualization type:
|
indicator |
Optional alias for |
palette |
Character string specifying a color palette. Default is automatically selected
based on |
thresholds |
Numeric vector of length 2 defining the RSE (%) thresholds for reliability
classification (see |
facet_scales |
Character string passed to |
title |
Optional title for the plot. If |
subtitle |
Optional subtitle for the plot. |
A ggplot object containing the thematic choropleth map.
library(fastsae) data(mys) # Create a synthetic spatial grid for demonstration if (requireNamespace("sf", quietly = TRUE)) { grid_sf <- sf::st_make_grid( sf::st_polygon(list(matrix(c(0,0, 6,0, 6,7, 0,7, 0,0), ncol = 2, byrow = TRUE))), cellsize = c(1, 1), what = "polygons" )[seq_len(nrow(mys))] mys_sf <- sf::st_sf(area = mys$area, geometry = grid_sf) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) # 2. Single model point estimate map (auto-detected key) p1 <- map_sae(fit_fh, sf_geom = mys_sf) # 3. Explicit key matching p2 <- map_sae(fit_fh, sf_geom = mys_sf, key = "area") # 4. Reliability classification map (BPS criteria: RSE <= 25%, 25-50%, > 50%) p3 <- map_sae(fit_fh, sf_geom = mys_sf, type = "reliability") # 5. Side-by-side comparison map: Direct Survey vs Model SAE p4 <- map_sae(fit_fh, sf_geom = mys_sf, type = "comparison") }library(fastsae) data(mys) # Create a synthetic spatial grid for demonstration if (requireNamespace("sf", quietly = TRUE)) { grid_sf <- sf::st_make_grid( sf::st_polygon(list(matrix(c(0,0, 6,0, 6,7, 0,7, 0,0), ncol = 2, byrow = TRUE))), cellsize = c(1, 1), what = "polygons" )[seq_len(nrow(mys))] mys_sf <- sf::st_sf(area = mys$area, geometry = grid_sf) # 1. Fit Fay-Herriot model fit_fh <- eblup_fh(y ~ x1 + x2, vardir = "vardir", data = mys) # 2. Single model point estimate map (auto-detected key) p1 <- map_sae(fit_fh, sf_geom = mys_sf) # 3. Explicit key matching p2 <- map_sae(fit_fh, sf_geom = mys_sf, key = "area") # 4. Reliability classification map (BPS criteria: RSE <= 25%, 25-50%, > 50%) p3 <- map_sae(fit_fh, sf_geom = mys_sf, type = "reliability") # 5. Side-by-side comparison map: Direct Survey vs Model SAE p4 <- map_sae(fit_fh, sf_geom = mys_sf, type = "comparison") }
A synthetic dataset containing the mean years of schooling for people with disabilities across 42 regencies/municipalities.
mysmys
A data frame with 42 rows and 9 variables with 10 domains as non-sampled areas.
regency municipality identifier
mean years of schooling people with disabilities (NA for unsampled areas)
variance sampling from the direct estimator for each area
relative standard error (%)
Number of Elementary Schools
Number of Junior High Schools
Number of Senior High Schools
Number of eligible samples
Weight
Simulated based on empirical characteristics of the National Socio-Economic Survey (Susenas), BPS-Statistics Indonesia.
A synthetic panel dataset containing the mean years of schooling for people with disabilities across 42 regencies/municipalities over 11 time periods (2016 - 2026).
mys_panelmys_panel
A data frame with 462 rows and 10 variables.
regency municipality identifier
year of observation (2016 to 2026)
mean years of schooling people with disabilities (NA for unsampled areas)
variance sampling from the direct estimator for each area
relative standard error (%)
Number of Elementary Schools
Number of Junior High Schools
Number of Senior High Schools
Number of eligible samples
Weight
Simulated panel data based on empirical characteristics of the National Socio-Economic Survey (Susenas), BPS-Statistics Indonesia.
A 42 by 42 row-standardized spatial proximity matrix for the 42 areas in mys.
mys_proxmatmys_proxmat
A square numeric matrix with 42 rows and 42 columns with values between 0 and 1.
Simulated based on contiguous administrative boundaries.
Provides standard R plot() dispatch for fastsae models.
Automatically routes to map_sae if spatial geometry is supplied,
to two-model comparison if a second fastsae model is provided, or
to autoplot for diagnostic and estimate plots.
## S3 method for class 'fastsae' plot(x, y = NULL, ...)## S3 method for class 'fastsae' plot(x, y = NULL, ...)
x |
An object of class |
y |
Optional second object (e.g. another |
... |
A ggplot object.
Print a fastsae object
## S3 method for class 'fastsae' print(x, ...)## S3 method for class 'fastsae' print(x, ...)
x |
An object of class |
... |
Additional arguments passed to print methods. |
The original object invisibly.
Print summary of a fastsae object
## S3 method for class 'summary.fastsae' print(x, ...)## S3 method for class 'summary.fastsae' print(x, ...)
x |
An object of class |
... |
Additional arguments. |
The original object invisibly.
Extract residuals from a fastsae object
## S3 method for class 'fastsae' residuals(object, ...)## S3 method for class 'fastsae' residuals(object, ...)
object |
An object of class |
... |
Additional arguments. |
Vector of residuals for sampled areas.
Creates (or updates) a Python environment with jax and numpyro for
hb_area(engine = "jax") and activates it for reticulate.
setup_numpyro_env(envname = "r-numpyro-gpu", method = "auto", device = "auto")setup_numpyro_env(envname = "r-numpyro-gpu", method = "auto", device = "auto")
envname |
Name of the conda or virtualenv environment. Default |
method |
|
device |
|
Invisible logical TRUE upon successful setup.
check_numpyro_available, hb_area
## Not run: setup_numpyro_env(device = "auto") ## End(Not run)## Not run: setup_numpyro_env(device = "auto") ## End(Not run)
A synthetic dataset containing 42 domains with multiple response variables
representing various probability distributions (Gaussian, Poisson, Binomial,
Beta, Negative Binomial, and Gamma). Designed for testing and benchmarking
generalized linear and spatial small area estimation models (HB / INLA).
It shares the 42-domain spatial structure of mys_proxmat.
data(sim_area)data(sim_area)
A data frame with 42 rows and 14 variables:
Integer domain identifier (1 to 42).
Continuous explanatory covariate.
Uniform explanatory covariate.
Gaussian direct estimator response with unsampled domains as NA.
Direct sampling variance for Gaussian Fay-Herriot model.
Count response (Poisson) with unsampled domains as NA.
Expected population count / exposure offset for Poisson model.
Number of successes (Binomial) with unsampled domains as NA.
Sample size / number of trials for Binomial model.
Continuous proportion response in (0, 1) for Beta regression.
Overdispersed count response for Negative Binomial model.
Skewed positive continuous response for Gamma regression.
Centroid x coordinate.
Centroid y coordinate.
Simulated using sim_area_data based on the spatial
proximity structure of mys_proxmat.
data(sim_area) head(sim_area)data(sim_area) head(sim_area)
Generates synthetic area-level datasets for small area estimation, including continuous (Gaussian, Gamma), count (Poisson, Negative Binomial), and proportion/rate responses (Binomial, Beta), driven by shared covariates and structured spatial random effects (BYM2 / SAR).
sim_area_data( D = 42, W = NULL, spatial_type = c("knn", "grid", "ring"), rho = 0.5, phi = 0.6, sigma_u = 0.5, beta = c(1, 0.8, -0.5), n_unsampled = 6, seed = NULL )sim_area_data( D = 42, W = NULL, spatial_type = c("knn", "grid", "ring"), rho = 0.5, phi = 0.6, sigma_u = 0.5, beta = c(1, 0.8, -0.5), n_unsampled = 6, seed = NULL )
D |
Integer. Number of domains (areas). Default is 42. |
W |
Optional spatial proximity or adjacency matrix of dimension |
spatial_type |
Character. Topology for simulated |
rho |
Numeric. Spatial autocorrelation autoregressive parameter ( |
phi |
Numeric. Proportion of spatial marginal variance relative to total area variance (BYM2 parameter, |
sigma_u |
Numeric. Overall standard deviation of domain random effects. Default is 0.5. |
beta |
Numeric vector of length 3 giving true regression coefficients |
n_unsampled |
Integer. Number of domains to mark as unsampled (where response variables are set to |
seed |
Optional integer. Random seed for reproducibility. |
An object of class c("fastsae_sim_data", "list") containing:
A data frame with columns: domain, x1, x2,
y_gaussian, vardir, y_poisson, exposure,
y_binomial, trials, y_beta, y_nbinomial,
y_gamma, x_coord, y_coord.
Binary adjacency matrix .
Row-standardized proximity matrix .
Coordinates of domain centroids.
True structured spatial random effect vector.
True unstructured random effect vector.
True total random effect vector.
True spatial variance fraction.
True spatial autoregressive parameter.
# 1. Simulate dataset with default KNN spatial structure sim <- sim_area_data(D = 40, spatial_type = "knn", seed = 123) print(sim) head(sim$data) # 2. Using an existing spatial matrix my_W <- sim_spatial_weights(D = 30, type = "grid") sim2 <- sim_area_data(W = my_W, seed = 456)# 1. Simulate dataset with default KNN spatial structure sim <- sim_area_data(D = 40, spatial_type = "knn", seed = 123) print(sim) head(sim$data) # 2. Using an existing spatial matrix my_W <- sim_spatial_weights(D = 30, type = "grid") sim2 <- sim_area_data(W = my_W, seed = 456)
A synthetic panel dataset containing 42 domains observed over 5 time periods
(2022 to 2026, total 210 observations). Features multiple response variables
representing various probability distributions (Gaussian, Poisson, Binomial,
Beta, Negative Binomial, and Gamma) driven by domain-level spatial autocorrelation
and first-order autoregressive AR(1) temporal dynamics. It shares the 42-domain
spatial structure of mys_proxmat and is formatted in domain-major order
for direct use in eblup_stfh.
data(sim_panel)data(sim_panel)
A data frame with 210 rows and 15 variables in domain-major order:
Integer domain identifier (1 to 42).
Year of observation (2022 to 2026).
Dynamic explanatory covariate with spatial & temporal variation.
Dynamic uniform explanatory covariate.
Gaussian direct estimator response with unsampled domains as NA.
Direct sampling variance for Gaussian Fay-Herriot model.
Count response (Poisson) with unsampled domains as NA.
Expected population count / exposure offset for Poisson model.
Number of successes (Binomial) with unsampled domains as NA.
Sample size / number of trials for Binomial model.
Continuous proportion response in (0, 1) for Beta regression.
Overdispersed count response for Negative Binomial model.
Skewed positive continuous response for Gamma regression.
Centroid x coordinate.
Centroid y coordinate.
Simulated using sim_series_data based on the spatial
proximity structure of mys_proxmat.
data(sim_panel) head(sim_panel)data(sim_panel) head(sim_panel)
Generates synthetic spatio-temporal panel datasets for small area estimation.
Combines domain-level spatial autocorrelation (SAR) with domain-specific first-order
autoregressive AR(1) temporal dynamics across time periods, producing multi-distribution
responses (Gaussian Fay-Herriot, Poisson, Binomial, Beta, Negative Binomial, Gamma).
sim_series_data( D = 42, T = 5, time_start = 2022, W = NULL, spatial_type = c("knn", "grid", "ring"), rho_s = 0.5, rho_t = 0.6, sigma_s = 0.4, sigma_t = 0.3, trend = c("linear", "random_walk", "ar1", "none"), trend_slope = 0.05, beta = c(1, 0.8, -0.5), n_unsampled = 4, prop_intermittent = 0.05, sort_order = c("domain-major", "time-major"), seed = NULL )sim_series_data( D = 42, T = 5, time_start = 2022, W = NULL, spatial_type = c("knn", "grid", "ring"), rho_s = 0.5, rho_t = 0.6, sigma_s = 0.4, sigma_t = 0.3, trend = c("linear", "random_walk", "ar1", "none"), trend_slope = 0.05, beta = c(1, 0.8, -0.5), n_unsampled = 4, prop_intermittent = 0.05, sort_order = c("domain-major", "time-major"), seed = NULL )
D |
Integer. Number of domains (areas). Default is 42. |
T |
Integer. Number of time periods ( |
time_start |
Integer. Starting year / time label. Default is 2022. |
W |
Optional spatial proximity or adjacency matrix of dimension |
spatial_type |
Character. Topology for simulated |
rho_s |
Numeric. Domain spatial autoregressive autocorrelation parameter ( |
rho_t |
Numeric. Temporal AR(1) autocorrelation parameter ( |
sigma_s |
Numeric. Standard deviation of domain spatial random effects ( |
sigma_t |
Numeric. Standard deviation of stationary spatio-temporal effects ( |
trend |
Character. Deterministric temporal trend type: |
trend_slope |
Numeric. Slope / scale of the temporal trend. Default is 0.05. |
beta |
Numeric vector of length 3 giving fixed regression coefficients |
n_unsampled |
Integer. Number of domains that are completely unsampled across all time periods. Default is 4. |
prop_intermittent |
Numeric. Proportion of domain-by-time observations to mark as intermittently missing (excluding persistent unsampled domains). Default is 0.05. |
sort_order |
Character. Row sorting order: |
seed |
Optional integer. Random seed for reproducibility. |
An object of class c("fastsae_sim_series", "list") containing:
A data frame of dimension with columns:
area, year, x1, x2, y_gaussian, vardir,
y_poisson, exposure, y_binomial, trials, y_beta,
y_nbinomial, y_gamma, x_coord, y_coord.
Binary adjacency matrix .
Row-standardized spatial weights matrix .
Centroid coordinates of the domains.
True domain spatial random effect vector of length .
True spatio-temporal random effect matrix of dimension .
List of true simulation parameters (rho_s, rho_t, sigma_s, sigma_t, beta, trend).
# 1. Simulate a 30-domain panel over 4 years sim_panel <- sim_series_data(D = 30, T = 4, time_start = 2021, seed = 123) print(sim_panel) head(sim_panel$data) # 2. Directly estimate Spatio-Temporal Fay-Herriot model (eblup_stfh) ## Not run: fit_stfh <- eblup_stfh( y_gaussian ~ x1 + x2, data = sim_panel$data, domain = ~area, time = ~year, vardir = ~vardir, W = sim_panel$W_std ) summary(fit_stfh) ## End(Not run)# 1. Simulate a 30-domain panel over 4 years sim_panel <- sim_series_data(D = 30, T = 4, time_start = 2021, seed = 123) print(sim_panel) head(sim_panel$data) # 2. Directly estimate Spatio-Temporal Fay-Herriot model (eblup_stfh) ## Not run: fit_stfh <- eblup_stfh( y_gaussian ~ x1 + x2, data = sim_panel$data, domain = ~area, time = ~year, vardir = ~vardir, W = sim_panel$W_std ) summary(fit_stfh) ## End(Not run)
Generates synthetic spatial proximity or adjacency matrices for small area estimation models. Supports k-nearest neighbors (KNN) on random 2D coordinates, regular grid contiguity (lattice), and 1D circular rings.
sim_spatial_weights( D = 40, type = c("knn", "grid", "ring"), style = c("B", "W"), k = 4, coords = NULL, seed = NULL )sim_spatial_weights( D = 40, type = c("knn", "grid", "ring"), style = c("B", "W"), k = 4, coords = NULL, seed = NULL )
D |
Integer. Number of small areas (domains). Default is 40. |
type |
Character. Topology type: |
style |
Character. Weight style: |
k |
Integer. Number of nearest neighbors per domain when |
coords |
Optional numeric matrix of dimension |
seed |
Optional integer. Random seed for reproducible coordinate generation. |
When type = "knn", coordinates are sampled from if not provided.
Each domain is connected to its nearest neighbors. To ensure a symmetric adjacency graph
required by GMRF spatial priors (INLA), edges are made mutual: domain and are
connected if is among the nearest neighbors of or vice versa.
When type = "grid", domains are placed on a regular lattice where
and . If ,
the first lattice points are retained. Rook contiguity (sharing a common edge) is used.
When type = "ring", domain is connected to and in a closed ring.
A square numeric matrix of dimension with row and column names
set to domain identifiers ("1", "2", ..., "D").
Attributes include "coords" (2D coordinates) and "type".
# 1. Binary adjacency matrix for 20 domains using KNN W_bin <- sim_spatial_weights(D = 20, type = "knn", k = 3, seed = 123) dim(W_bin) table(W_bin) # 2. Row-standardized matrix on a regular grid W_std <- sim_spatial_weights(D = 25, type = "grid", style = "W") rowSums(W_std)# 1. Binary adjacency matrix for 20 domains using KNN W_bin <- sim_spatial_weights(D = 20, type = "knn", k = 3, seed = 123) dim(W_bin) table(W_bin) # 2. Row-standardized matrix on a regular grid W_std <- sim_spatial_weights(D = 25, type = "grid", style = "W") rowSums(W_std)
Evaluates whether spatial autocorrelation is present in direct domain estimates
and regression residuals, conducts Lagrange Multiplier (LM) tests (Anselin, 1988),
and performs comparative model fit tests between the standard Fay-Herriot (eblup_fh)
and Spatial Fay-Herriot (eblup_sfh) models. Provides an explicit,
automated recommendation on whether a spatial model is statistically necessary.
spatial_test( formula, vardir = NULL, data, W = NULL, alpha = 0.05, alternative = c("greater", "two.sided", "less") )spatial_test( formula, vardir = NULL, data, W = NULL, alpha = 0.05, alternative = c("greater", "two.sided", "less") )
formula |
Regression formula describing the model (e.g. |
vardir |
Optional vector, column name, or formula referencing sampling variances of the direct estimator. Required for full model comparison (Standard FH vs Spatial FH). |
data |
A |
W |
Proximity or spatial adjacency matrix. If |
alpha |
Significance level for hypothesis tests (default is 0.05). |
alternative |
Alternative hypothesis for Moran's I ( |
Moran's uses the randomisation variance of Cliff and Ord (1981); the LM-error and
LM-lag statistics follow Anselin (1988). These tests assume homoscedastic OLS errors, whereas
direct estimates have domain-specific sampling variances, so they are descriptive. The
recommendation therefore rests on one test, so that its false positive rate is alpha:
with vardir, the likelihood ratio test of between eblup_fh
and eblup_sfh fitted by ML (which accounts for the sampling variances);
without it, the LM-error test.
An object of class c("fastsae_spatial_test", "list") containing:
Global Moran's I test results on direct response variable .
Moran's I, Anselin LM-Error, and Anselin LM-Lag test results on regression residuals.
ML log-likelihoods, AIC, BIC, and the likelihood ratio test (LRT) of
comparing standard vs spatial FH, both fitted by ML (if vardir provided).
Logical recommendation, from a single test at level alpha
(see Details).
The test behind spatial_recommended: "lrt" or "lm_error".
Character string explaining the recommendation.
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer Academic Publishers.
Cliff, A. D., & Ord, J. K. (1981). Spatial Processes: Models & Applications. Pion London.
Petrucci, A., & Salvati, N. (2006). Small area estimation for spatial data in R. Statistical Methods & Applications, 14(3), 391-407.
library(fastsae) data(mys) data(mys_proxmat) # Run spatial diagnostics on simulated survey data st <- spatial_test( formula = y ~ x1 + x2, vardir = "vardir", data = mys, W = mys_proxmat ) print(st)library(fastsae) data(mys) data(mys_proxmat) # Run spatial diagnostics on simulated survey data st <- spatial_test( formula = y ~ x1 + x2, vardir = "vardir", data = mys, W = mys_proxmat ) print(st)
Summarize a fastsae object
## S3 method for class 'fastsae' summary(object, ...)## S3 method for class 'fastsae' summary(object, ...)
object |
An object of class |
... |
Additional arguments. |
An object of class summary.fastsae.