| Title: | Integrated Analysis Toolkit for Health, Climate, and Environmental Data in Brazil: Reproducible Workflows for Climate-Health Research |
|---|---|
| Description: | climasus4r is a comprehensive R toolkit for integrated analysis of health, climate, and environmental data in Brazil. The package automates the entire data pipeline: (1) importing and cleaning health data from the Brazilian Unified Health System (SUS) across six systems (SIM, SIH, SINAN, SIA, CNES, SINASC); (2) integrating climate data (INMET, ERA5), air quality (AQI), environmental data (MapBiomas), and socioeconomic indicators (IBGE); (3) performing flexible spatiotemporal aggregation at multiple scales; (4) constructing reproducible analytical pipelines (RAPs) that ensure transparency and replicability. Designed for researchers studying climate-health interactions, environmental vulnerability, and adaptation strategies in the Brazilian context. Supports multilingual output (Portuguese, Spanish, English) and parallel processing for large datasets. |
| Authors: | Max Anjos [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-6394-1324>), Thaua Menezes [ctb] (ORCID: <https://orcid.org/0000-0002-3015-2270>), Marlon Faria [ctb] (ORCID: <https://orcid.org/0000-0002-9485-4079>) |
| Maintainer: | Max Anjos <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0 |
| Built: | 2026-07-10 18:21:27 UTC |
| Source: | https://github.com/ByMaxAnjos/climasus4r |
Subsetting method for climasus_df
## S3 method for class 'climasus_df' x[i, j, drop = FALSE]## S3 method for class 'climasus_df' x[i, j, drop = FALSE]
x |
A climasus_df object |
i |
Row indices |
j |
Column indices |
drop |
Logical |
Column extraction for climasus_df
## S3 method for class 'climasus_df' x[[i]]## S3 method for class 'climasus_df' x[[i]]
x |
A climasus_df object |
i |
Column index or name |
Column assignment for climasus_df
## S3 replacement method for class 'climasus_df' x$name <- value## S3 replacement method for class 'climasus_df' x$name <- value
x |
A climasus_df object |
name |
Column name |
value |
New column values |
Coerce climasus_df to plain data.frame (strips metadata)
## S3 method for class 'climasus_df' as.data.frame(x, ...)## S3 method for class 'climasus_df' as.data.frame(x, ...)
x |
A climasus_df object |
... |
Additional arguments (ignored) |
Extract coefficients from a climasus_dlnm model
## S3 method for class 'climasus_dlnm' coef(object, ...)## S3 method for class 'climasus_dlnm' coef(object, ...)
object |
A |
... |
Passed to |
Named numeric vector of GLM coefficients.
Extract pooled coefficients from a climasus_metaregression object
## S3 method for class 'climasus_metaregression' coef(object, ...)## S3 method for class 'climasus_metaregression' coef(object, ...)
object |
A |
... |
Passed to |
Named numeric vector of meta-regression coefficients.
Extract pooled coefficients from a climasus_pool object
## S3 method for class 'climasus_pool' coef(object, ...)## S3 method for class 'climasus_pool' coef(object, ...)
object |
A |
... |
Passed to |
Named numeric vector of pooled cross-basis coefficients.
Extract VI scores as a named numeric vector
## S3 method for class 'climasus_vi' coef(object, ...)## S3 method for class 'climasus_vi' coef(object, ...)
object |
A |
... |
Unused. |
Named numeric vector (city → vi_score).
Return daily rows where at least one coldwave method is active
cw_active_days(cw_result)cw_active_days(cw_result)
cw_result |
A |
A filtered tibble from cw_result$daily.
Count coldwave events by year, station, and method
cw_count_by_year(cw_result)cw_count_by_year(cw_result)
cw_result |
A |
A tibble with columns year, station_code, station_name, method, n_events, total_days_cw, mean_duration.
Extract coldwave events table from a climasus_cw result
cw_get_events(cw_result, method_filter = NULL)cw_get_events(cw_result, method_filter = NULL)
cw_result |
A |
method_filter |
Character vector. If supplied, keep only these methods. |
A tibble of coldwave events.
Return daily rows where at least one heatwave method is active
hw_active_days(hw_result)hw_active_days(hw_result)
hw_result |
A |
A filtered tibble from hw_result$daily.
Count heatwave events by year, station, and method
hw_count_by_year(hw_result)hw_count_by_year(hw_result)
hw_result |
A |
A tibble with columns year, station_code, station_name, method, n_events, total_days_hw, mean_duration.
Extract heatwave events table from a climasus_hw result
hw_get_events(hw_result, method_filter = NULL)hw_get_events(hw_result, method_filter = NULL)
hw_result |
A |
method_filter |
Character vector. If supplied, keep only these methods. |
A tibble of heatwave events.
Applies the fitted XGBoost model to a new data frame. The new data must
contain all feature columns used during training (see
object$meta$feature_cols).
## S3 method for class 'climasus_ml' predict(object, newdata, ...)## S3 method for class 'climasus_ml' predict(object, newdata, ...)
object |
A |
newdata |
A data frame with the same feature columns as the training data. Missing features trigger an informative error. |
... |
Unused. |
A numeric vector of predictions (in the natural scale of the objective: counts for Poisson, values for squarederror, probabilities for binary logistic).
Print a climasus_af object
## S3 method for class 'climasus_af' print(x, ...)## S3 method for class 'climasus_af' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_burden object
## S3 method for class 'climasus_burden' print(x, ...)## S3 method for class 'climasus_burden' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_casecrossover object
## S3 method for class 'climasus_casecrossover' print(x, ...)## S3 method for class 'climasus_casecrossover' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print method for climasus_df
## S3 method for class 'climasus_df' print(x, n = 10, ...)## S3 method for class 'climasus_df' print(x, n = 10, ...)
x |
A climasus_df object |
n |
Integer. Number of rows to print |
... |
Additional arguments passed to print |
Print a climasus_dlnm model
## S3 method for class 'climasus_dlnm' print(x, ...)## S3 method for class 'climasus_dlnm' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_excess object
## S3 method for class 'climasus_excess' print(x, ...)## S3 method for class 'climasus_excess' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_its object
## S3 method for class 'climasus_its' print(x, ...)## S3 method for class 'climasus_its' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_metaregression object
## S3 method for class 'climasus_metaregression' print(x, ...)## S3 method for class 'climasus_metaregression' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_ml object
## S3 method for class 'climasus_ml' print(x, n_imp = 10L, ...)## S3 method for class 'climasus_ml' print(x, n_imp = 10L, ...)
x |
A |
n_imp |
Integer. Number of top features to show. Default |
... |
Unused. |
x invisibly.
Print a climasus_pool object
## S3 method for class 'climasus_pool' print(x, ...)## S3 method for class 'climasus_pool' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_sensitivity object
## S3 method for class 'climasus_sensitivity' print(x, ...)## S3 method for class 'climasus_sensitivity' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Displays a formatted summary of the spatiotemporal Bayesian model fit, including model specification, goodness-of-fit statistics, posterior fixed-effect estimates with 95% credible intervals, and a summary of relative risks across the space-time grid.
## S3 method for class 'climasus_spacetime_bayes' print(x, n_fixed = 10L, ...)## S3 method for class 'climasus_spacetime_bayes' print(x, n_fixed = 10L, ...)
x |
A |
n_fixed |
Integer. Maximum number of fixed-effect rows to display.
Default |
... |
Additional arguments (ignored). |
Invisibly returns x.
Displays a formatted summary of exceedance probabilities including the number of municipality-time cells that exceed each RR threshold with posterior probability greater than 0.80.
## S3 method for class 'climasus_spacetime_exceedance' print(x, n_rows = 10L, ...)## S3 method for class 'climasus_spacetime_exceedance' print(x, n_rows = 10L, ...)
x |
A |
n_rows |
Integer. Maximum number of exceedance table rows to display.
Default |
... |
Additional arguments (ignored). |
Invisibly returns x.
Displays a formatted summary of space-time predictions, including the number of predicted observations, the forward horizon, municipality and time-index range, and a preview of the predictions table.
## S3 method for class 'climasus_spacetime_pred' print(x, n_rows = 6L, ...)## S3 method for class 'climasus_spacetime_pred' print(x, n_rows = 6L, ...)
x |
A |
n_rows |
Integer. Maximum number of prediction rows to display in the
preview. Default |
... |
Additional arguments (ignored). |
Invisibly returns x.
Displays a formatted summary of the Bayesian spatial model fit, including DIC, effective MCMC sample size (or NA for INLA-based models), model specification, and the top fixed effects with posterior means and 95\ credible intervals.
## S3 method for class 'climasus_spatial_bayes' print(x, n_fixed = 10L, ...)## S3 method for class 'climasus_spatial_bayes' print(x, n_fixed = 10L, ...)
x |
A |
n_fixed |
Integer. Maximum number of fixed-effect rows to display.
Default |
... |
Additional arguments (ignored). |
Invisibly returns x.
Displays a formatted summary of the global Moran's I test and the LISA cluster counts.
## S3 method for class 'climasus_spatial_moran' print(x, ...)## S3 method for class 'climasus_spatial_moran' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Displays a formatted summary of the spatial regression model, including the model type, spatial parameters (rho / lambda), coefficient table, AIC comparison with OLS, and the Moran test result on residuals.
## S3 method for class 'climasus_spatial_reg' print(x, n_coef = 10L, ...)## S3 method for class 'climasus_spatial_reg' print(x, n_coef = 10L, ...)
x |
A |
n_coef |
Integer. Maximum number of coefficient rows to display.
Default |
... |
Additional arguments (ignored). |
Invisibly returns x.
Print a climasus_spatial_scan object
## S3 method for class 'climasus_spatial_scan' print(x, ...)## S3 method for class 'climasus_spatial_scan' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_swot object
## S3 method for class 'climasus_swot' print(x, ...)## S3 method for class 'climasus_swot' print(x, ...)
x |
A |
... |
Ignored. |
Print a climasus_ts_quality object
## S3 method for class 'climasus_ts_quality' print(x, ...)## S3 method for class 'climasus_ts_quality' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Print a climasus_vi object
## S3 method for class 'climasus_vi' print(x, ...)## S3 method for class 'climasus_vi' print(x, ...)
x |
A |
... |
Unused. |
x invisibly.
Displays a compact summary of the spatial weights object including the number of regions, islands, weight style, and neighbour statistics.
## S3 method for class 'climasus_weights' print(x, ...)## S3 method for class 'climasus_weights' print(x, ...)
x |
A |
... |
Ignored. |
x invisibly.
Row binding for climasus_df objects
## S3 method for class 'climasus_df' rbind(..., deparse.level = 1)## S3 method for class 'climasus_df' rbind(..., deparse.level = 1)
... |
climasus_df objects to combine |
deparse.level |
Integer |
Summarise a climasus_af object
## S3 method for class 'climasus_af' summary(object, ...)## S3 method for class 'climasus_af' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_burden object
## S3 method for class 'climasus_burden' summary(object, ...)## S3 method for class 'climasus_burden' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_casecrossover object
## S3 method for class 'climasus_casecrossover' summary(object, ...)## S3 method for class 'climasus_casecrossover' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_dlnm model
## S3 method for class 'climasus_dlnm' summary(object, ...)## S3 method for class 'climasus_dlnm' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_excess object
## S3 method for class 'climasus_excess' summary(object, ...)## S3 method for class 'climasus_excess' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_its object
## S3 method for class 'climasus_its' summary(object, ...)## S3 method for class 'climasus_its' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_metaregression object
## S3 method for class 'climasus_metaregression' summary(object, ...)## S3 method for class 'climasus_metaregression' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_ml object
## S3 method for class 'climasus_ml' summary(object, ...)## S3 method for class 'climasus_ml' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_pool object
## S3 method for class 'climasus_pool' summary(object, ...)## S3 method for class 'climasus_pool' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_sensitivity object
## S3 method for class 'climasus_sensitivity' summary(object, ...)## S3 method for class 'climasus_sensitivity' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Alias for print.climasus_spacetime_bayes().
## S3 method for class 'climasus_spacetime_bayes' summary(object, ...)## S3 method for class 'climasus_spacetime_bayes' summary(object, ...)
object |
A |
... |
Additional arguments passed to |
Invisibly returns object.
Alias for print.climasus_spacetime_exceedance().
## S3 method for class 'climasus_spacetime_exceedance' summary(object, ...)## S3 method for class 'climasus_spacetime_exceedance' summary(object, ...)
object |
A |
... |
Additional arguments passed to
|
Invisibly returns object.
Alias for print.climasus_spacetime_pred().
## S3 method for class 'climasus_spacetime_pred' summary(object, ...)## S3 method for class 'climasus_spacetime_pred' summary(object, ...)
object |
A |
... |
Additional arguments passed to |
Invisibly returns object.
Alias for print.climasus_spatial_bayes().
## S3 method for class 'climasus_spatial_bayes' summary(object, ...)## S3 method for class 'climasus_spatial_bayes' summary(object, ...)
object |
A |
... |
Additional arguments passed to |
Invisibly returns object.
Returns the global statistics data frame and the local LISA data frame.
## S3 method for class 'climasus_spatial_moran' summary(object, ...)## S3 method for class 'climasus_spatial_moran' summary(object, ...)
object |
A |
... |
Additional arguments (ignored). |
A list with elements global and local, invisibly.
Prints the model and returns the key tables invisibly.
## S3 method for class 'climasus_spatial_reg' summary(object, ...)## S3 method for class 'climasus_spatial_reg' summary(object, ...)
object |
A |
... |
Additional arguments passed to |
A named list with elements coefficients, impacts,
moran_residuals, aic, and lm_aic, invisibly.
Summarise a climasus_spatial_scan object
## S3 method for class 'climasus_spatial_scan' summary(object, ...)## S3 method for class 'climasus_spatial_scan' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_swot object
## S3 method for class 'climasus_swot' summary(object, ...)## S3 method for class 'climasus_swot' summary(object, ...)
object |
A |
... |
Ignored. |
Summarise a climasus_ts_quality object
## S3 method for class 'climasus_ts_quality' summary(object, ...)## S3 method for class 'climasus_ts_quality' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Summarise a climasus_vi object
## S3 method for class 'climasus_vi' summary(object, ...)## S3 method for class 'climasus_vi' summary(object, ...)
object |
A |
... |
Unused. |
object invisibly.
Alias for print.climasus_weights().
## S3 method for class 'climasus_weights' summary(object, ...)## S3 method for class 'climasus_weights' summary(object, ...)
object |
A |
... |
Ignored. |
object invisibly.
Embeds sus_meta as a JSON string in the Arrow schema metadata field
"sus_meta". This ensures the metadata survives all downstream dplyr
verbs (filter, mutate, group_by, etc.) because Arrow schema metadata
travels with the data.
sus_as_arrow(df)sus_as_arrow(df)
df |
A |
An Arrow Table with sus_meta embedded in the schema.
## Not run: arrow_df <- sus_data_standardize(df) |> sus_as_arrow() result <- sus_data_aggregate(arrow_df, time_unit = "month") ## End(Not run)## Not run: arrow_df <- sus_data_standardize(df) |> sus_as_arrow() result <- sus_data_aggregate(arrow_df, time_unit = "month") ## End(Not run)
Copies the data to a DuckDB connection and stores sus_meta in a helper
table named .__sus_meta__. This allows sus_data_aggregate() to
recover the metadata automatically.
sus_as_duckdb(df, con, name = "sus_data", overwrite = TRUE)sus_as_duckdb(df, con, name = "sus_data", overwrite = TRUE)
df |
A |
con |
A DuckDB |
name |
Character; name for the DuckDB table. Defaults to |
overwrite |
Logical. Overwrite existing table? Default |
A tbl_dbi referencing the DuckDB table.
## Not run: con <- duckdb::dbConnect(duckdb::duckdb()) duck_tbl <- sus_data_standardize(df) |> sus_as_duckdb(con) result <- sus_data_aggregate(duck_tbl, time_unit = "month") ## End(Not run)## Not run: con <- duckdb::dbConnect(duckdb::duckdb()) duck_tbl <- sus_data_standardize(df) |> sus_as_duckdb(con) result <- sus_data_aggregate(duck_tbl, time_unit = "month") ## End(Not run)
Clear the Climasus4r cache
sus_cache_clear( cache_dir = "~/.climasus4r_cache", older_than_days = NULL, verbose = TRUE )sus_cache_clear( cache_dir = "~/.climasus4r_cache", older_than_days = NULL, verbose = TRUE )
cache_dir |
Character. Cache directory to clear. Default is "~/.climasus4r_cache". |
older_than_days |
Numeric. Only clear files older than this many days. NULL clears all. |
verbose |
Logical. If TRUE, prints information about what was cleared. |
## Not run: # Clear all cache sus_cache_clear() # Clear only files older than 90 days sus_cache_clear(older_than_days = 90) ## End(Not run)## Not run: # Clear all cache sus_cache_clear() # Clear only files older than 90 days sus_cache_clear(older_than_days = 90) ## End(Not run)
Get cache information
sus_cache_info(cache_dir = "~/.climasus4r_cache", verbose = TRUE)sus_cache_info(cache_dir = "~/.climasus4r_cache", verbose = TRUE)
cache_dir |
Character. Cache directory to inspect. Default is "~/.climasus4r_cache". |
verbose |
Logical. If TRUE, prints detailed information. |
A list with cache statistics.
## Not run: cache_info <- sus_cache_info() ## End(Not run)## Not run: cache_info <- sus_cache_info() ## End(Not run)
Enriches health data with socioeconomic indicators from Brazilian Census using
the censobr package. Provides aggregation of microdata to municipality level. Supports multiple census datasets (population, households,
families, mortality, emigration) with intelligent caching and optimized performance for large datasets using Arrow/Parquet format.
sus_census_join( df, dataset = "population", tracts_dataset = "Basico", year = 2010, census_vars = NULL, aggregation_fun = "sum", join_muni_col = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/census", lang = "pt", translate_columns = TRUE, standardize_values = TRUE, verbose = TRUE )sus_census_join( df, dataset = "population", tracts_dataset = "Basico", year = 2010, census_vars = NULL, aggregation_fun = "sum", join_muni_col = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/census", lang = "pt", translate_columns = TRUE, standardize_values = TRUE, verbose = TRUE )
df |
A |
dataset |
Character string specifying the census dataset to use. Options:
|
tracts_dataset |
Character string. Relevant only when |
year |
Integer specifying census year. Options: |
census_vars |
Character vector specifying census variables to add. Use |
aggregation_fun |
Character. Method to aggregate microdata to municipality level:
|
join_muni_col |
Character string specifying the column in df containing the 6 or 7-digit IBGE municipality code. If |
use_cache |
Logical. If |
cache_dir |
Character string specifying cache directory path. Defaults to
|
lang |
Character string specifying language for messages. Options: |
translate_columns |
Logical. If TRUE, translates column names. Default is TRUE. |
standardize_values |
Logical. If TRUE, standardizes categorical values. Default is TRUE. |
verbose |
Logical. If |
Integration with censobr package:
This function is a wrapper around censobr's dataset-specific functions
(read_population(), read_households(), etc.), providing seamless integration
with the climasus4r ecosystem.
Geographic Columns: The function automatically inherits and matches geographic columns following the geobr/censobr standard:
code_muni - 7-digit municipality code
code_state - 2-digit state code
abbrev_state - State abbreviation (e.g., "AM")
name_state - State name
code_region - Region code
name_region - Region name
code_weighting - Weighting area code
Automatic Column Detection:
If join_muni_col = NULL, the function automatically detects the appropriate code municipality
column based on common SUS patterns:
Municipality: residence_municipality_code, municipality_code,
codigo_municipio, CODMUNRES, etc.
Performance Optimization: The function uses Arrow/Parquet format for efficient larger-than-memory dataset handling:
Downloads data only once (cached locally)
Filters municipalities BEFORE loading to RAM
Uses dplyr::collect() only after filtering
Uses sfarrow pak for spatial filtering
Spatial Data Support:
If df is an sf object from sus_spatial_join(), geometries are preserved in the output.
Returns the input data.frame or sf object with additional columns. If the input is an sf object, the spatial geometry and CRS are strictly preserved through a join.
Pereira, Rafael H. M.; Barbosa, Rogerio J. (2023) censobr: Download Data from Brazil’s Population Census. R package version v0.4.0, https://CRAN.R-project.org/package=censobr. DOI: 10.32614/CRAN.package.censobr.
## Not run: library(climasus4r) # Prepare spatial health data sf_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize(lang = "pt") %>% sus_spatial_join(level = "munic", lang = "pt") # Add census population data sf_enriched <- sus_census_join( df = sf_sim, dataset = "population", census_vars = c("V0001", "V0002"), year = 2010, lang = "pt" ) ## End(Not run)## Not run: library(climasus4r) # Prepare spatial health data sf_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize(lang = "pt") %>% sus_spatial_join(level = "munic", lang = "pt") # Add census population data sf_enriched <- sus_census_join( df = sf_sim, dataset = "population", census_vars = c("V0001", "V0002"), year = 2010, lang = "pt" ) ## End(Not run)
Opens an interactive HTML interface to explore Brazilian Census variables and copy codes for use with sus_census_join().
sus_census_select( dataset = "all", year = 2010, lang = "pt", output = "browser", verbose = TRUE )sus_census_select( dataset = "all", year = 2010, lang = "pt", output = "browser", verbose = TRUE )
dataset |
Character string specifying the census dataset. Options:
|
year |
Integer specifying census year. Options: |
lang |
Character string specifying language. Options: |
output |
Character string specifying output format. Options:
|
verbose |
Logical. If |
This function helps users discover which census variables are available.
The interactive interface allows easy copying of variable codes for use
in sus_census_join(vars = ...).
Depending on output:
"browser": Opens HTML interface, returns invisible data.frame
"console": Prints summary, returns invisible data.frame
"codes": Returns character vector of variable codes
## Not run: # Open interactive explorer for all datasets sus_census_select() # Explore only population variables sus_census_select(dataset = "population") # Get variable codes for programmatic use vars <- sus_census_select( dataset = "population", output = "codes", lang = "en" ) # Use in sus_census_join data <- sus_census_join( df = my_data, vars = vars, dataset = "population", year = 2010 ) ## End(Not run)## Not run: # Open interactive explorer for all datasets sus_census_select() # Explore only population variables sus_census_select(dataset = "population") # Get variable codes for programmatic use vars <- sus_census_select( dataset = "population", output = "codes", lang = "en" ) # Use in sus_census_join data <- sus_census_join( df = my_data, vars = vars, dataset = "population", year = 2010 ) ## End(Not run)
Launch the climasus4r AI Assistant
sus_chat()sus_chat()
sus_climate_aggregate() aggregates meteorological data to DATASUS health data
using epidemiologically rigorous temporal strategies. The function links each
health record to the nearest climate station (by Euclidean distance) and applies
the requested temporal window.
sus_climate_aggregate( health_data, climate_data, climate_var = "all", time_unit = "day", temporal_strategy = "exact", climate_region = "auto", window_days = NULL, lag_days = NULL, offset_days = NULL, temp_base = NULL, gdd_temp_var = "tair_dry_bulb_c", min_obs = 0.7, threshold_value = NULL, threshold_direction = "above", weights = NULL, lang = "pt", verbose = TRUE )sus_climate_aggregate( health_data, climate_data, climate_var = "all", time_unit = "day", temporal_strategy = "exact", climate_region = "auto", window_days = NULL, lag_days = NULL, offset_days = NULL, temp_base = NULL, gdd_temp_var = "tair_dry_bulb_c", min_obs = 0.7, threshold_value = NULL, threshold_direction = "above", weights = NULL, lang = "pt", verbose = TRUE )
health_data |
A |
climate_data |
A |
climate_var |
Character vector with climate variables to aggregate.
Use Available variables are grouped as follows: Atmospheric pressure:
Air temperature:
Dew point temperature:
Relative humidity:
Precipitation:
Wind:
Solar radiation:
Biometeorological indices:
Thermal indices (degree-days):
Derived variables:
@section Notes:
|
time_unit |
Temporal aggregation unit for raw climate data before join.
Options: |
temporal_strategy |
Temporal matching strategy. Options:
|
climate_region |
Character. Climate classification for parameter adaptation.
Options: |
window_days |
Integer. Number of days in window for |
lag_days |
Integer vector. Specific lags for |
offset_days |
Integer vector of length 2 for |
temp_base |
Numeric. Temperature base for |
gdd_temp_var |
Character. Temperature column for |
min_obs |
Numeric (0 to 1). Minimum proportion of valid observations required within window. Default: 0.7 (70%). |
threshold_value |
Numeric. Threshold for |
threshold_direction |
Character: |
weights |
Numeric vector (optional) for |
lang |
Language for messages: |
verbose |
Logical. If |
The choice of strategy should reflect the hypothesized biological mechanism:
exact: Immediate effects (heat stroke, hemorrhagic stroke)
discrete_lag: Known delayed effect (e.g., temperature 7 days before influences dengue)
moving_window: Cumulative exposure without specific lag.
offset_window: Defined incubation period (e.g., temperature 14-7 days before death)
distributed_lag: Distributed lag analysis (DLNM); generates exposure matrix for dlnm::crossbasis()
degree_days: Thermal threshold for vector development. GDD above temperature base accumulates over window_days.
seasonal: Seasonal climate patterns for ecological or long-term studies
threshold_exceedance: Counts days exceeding threshold (ideal for heatwaves)
cold_wave_exceedance: Counts days below threshold (ideal for cold extremes in southern regions)
weighted_window: Weighted mean modeling biological decay of exposure
The function automatically adapts to Brazil's diverse climates:
Tropical (North, Northeast): Mean temperature 24-28degC, recommended temp_base 20degC (human health), heatwave threshold Tmax > 35degC, high autocorrelation.
Subtropical (Center-West, Southeast): Mean temperature 18-26degC, recommended temp_base 18degC, heatwave threshold Tmax > 32degC, moderate autocorrelation.
Temperate (South): Mean temperature 12-24degC, recommended temp_base 15degC, heatwave threshold Tmax > 30degC, coldwave threshold Tmin < 5degC (critical), low autocorrelation.
This function uses retroactive windows (t-W, t), never symmetric windows (t-W, t+W). The climate of day t+7 cannot cause a health event on day t. This design prevents look-ahead bias, a common methodological error in environmental epidemiology.
A climasus_df (tibble) with original health data and integrated climate
variables as new columns. Geometry is preserved if input is sf.
Gasparrini, A. (2011). Distributed lag linear and non-linear models in R: the package dlnm. Journal of Statistical Software, 43(8), 1-20.
Silveira, I. H., et al. (2023). Heat waves and mortality in the Brazilian Amazon. International Journal of Hygiene and Environmental Health, 248, 114109.
Marengo, J. A., et al. (2023). A cold wave of winter 2021 in central South America. Climate Dynamics, 61, 3-4.
## Not run: # Prepare data df_health <- sus_data_import() |> sus_data_clean_encoding() |> sus_data_standardize() |> sus_spatial_join(level = "munic") df_climate <- sus_climate_inmet(years = 2023, uf = "AM") |> sus_climate_fill_inmet(target_var = "all", parallel = TRUE) # Example 1: Exact match (same-day temperature) df_exact <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, climate_var = "tair_dry_bulb_c", temporal_strategy = "exact" ) # Example 2: Moving window (cumulative exposure, RECOMMENDED) df_moving <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, temporal_strategy = "moving_window", window_days = 14 ) # Example 3: Regional adaptation (auto-detect) df_regional <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, climate_region = "auto", temporal_strategy = "threshold_exceedance", window_days = 7 ) # Example 4: Cold waves (southern regions) df_coldwave <- sus_climate_aggregate( health_data = df_health_south, climate_data = df_climate_south, climate_region = "temperate", temporal_strategy = "cold_wave_exceedance", window_days = 7, threshold_value = 5 ) ## End(Not run)## Not run: # Prepare data df_health <- sus_data_import() |> sus_data_clean_encoding() |> sus_data_standardize() |> sus_spatial_join(level = "munic") df_climate <- sus_climate_inmet(years = 2023, uf = "AM") |> sus_climate_fill_inmet(target_var = "all", parallel = TRUE) # Example 1: Exact match (same-day temperature) df_exact <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, climate_var = "tair_dry_bulb_c", temporal_strategy = "exact" ) # Example 2: Moving window (cumulative exposure, RECOMMENDED) df_moving <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, temporal_strategy = "moving_window", window_days = 14 ) # Example 3: Regional adaptation (auto-detect) df_regional <- sus_climate_aggregate( health_data = df_health, climate_data = df_climate, climate_region = "auto", temporal_strategy = "threshold_exceedance", window_days = 7 ) # Example 4: Cold waves (southern regions) df_coldwave <- sus_climate_aggregate( health_data = df_health_south, climate_data = df_climate_south, climate_region = "temperate", temporal_strategy = "cold_wave_exceedance", window_days = 7, threshold_value = 5 ) ## End(Not run)
Computes climate anomalies by comparing observed meteorological data from
sus_climate_inmet() against 30-year climatological normals from
sus_climate_normals(). Three anomaly types are supported: absolute
(obs − normal), relative ((obs − normal) / |normal| × 100 %), and
standardized z-score ((obs − normal) / σ_obs). The result is a climasus_df
ready for epidemiological modelling with sus_mod_dlnm(),
sus_climate_compute_heatwaves(), or sus_mod_vulnerability_index().
sus_climate_anomaly( observed, normals, vars = NULL, method = c("absolute", "relative", "standardized", "all"), time_scale = c("monthly", "decadal"), station_col = "station_code", date_col = "date", lang = c("pt", "en", "es"), verbose = TRUE )sus_climate_anomaly( observed, normals, vars = NULL, method = c("absolute", "relative", "standardized", "all"), time_scale = c("monthly", "decadal"), station_col = "station_code", date_col = "date", lang = c("pt", "en", "es"), verbose = TRUE )
observed |
A |
normals |
A |
vars |
Named character vector mapping observed column names to
normals |
method |
Character. Anomaly computation method: |
time_scale |
Character. Temporal resolution for the anomaly:
|
station_col |
Character. Name of the station identifier column in
|
date_col |
Character. Name of the date or datetime column in
|
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_df at stage "climate" and type "anomaly". One row
per station × year × month (or × decade when time_scale = "decadal").
Key columns:
station_colStation identifier (same as station_col argument).
yearCalendar year of the observation.
month_numMonth number (1–12).
month_namePortuguese month name, ASCII.
decade_numDecade within month (1, 2, or 3). Present only when
time_scale = "decadal".
{v}_obsObserved monthly/decadal value (mean or sum depending on variable type).
{v}_normalClimatological normal value.
{v}_anomalyAbsolute anomaly: obs − normal.
{v}_anomaly_pctRelative anomaly (\
|normal| × 100. Only when method ∈ c("relative", "all").
{v}_anomaly_stdStandardized anomaly (z-score):
(obs − normal) / σ_obs, where σ is the inter-annual SD of monthly
observations for each station × month. Only when
method ∈ c("standardized", "all").
Multi-city comparability: standardized anomalies make DLNM exposure-response curves poolable across cities with very different baseline climates (Manaus vs. Porto Alegre).
Extreme event attribution: anomaly peaks pinpoint the dates to correlate with DATASUS hospitalization or mortality surges.
Climate trend detection: a positive trend in temperature anomalies
captures local warming for the IPCC Exposure pillar in
sus_mod_vulnerability_index().
Vector-borne and waterborne diseases: precipitation anomalies detect flood/drought episodes — with a 2–4 week lag — relevant to dengue, leptospirosis, and diarrheal disease in SINAN.
Thermal comfort indices: anomaly-adjusted temperature feeds DLNM models without confounding by mean inter-city temperature differences.
| Method | Formula | Primary use |
"absolute" |
obs − normal | Temperature anomalies (°C) |
"relative" |
(obs − normal) / |normal| × 100 | Precipitation anomaly (%) |
"standardized" |
(obs − normal) / σ_obs | Multi-city pooling, DLNM input |
"all" |
All three | Exploratory analysis |
sus_climate_normals(), sus_climate_normals_meta(),
sus_climate_inmet(), sus_climate_aggregate(),
sus_mod_dlnm(), sus_mod_vulnerability_index()
## Not run: # 1. Download data obs <- sus_climate_inmet(years = 2018:2023, uf = "RJ") norm <- sus_climate_normals(period = "1991-2020", target_var = c("t_max", "t_min", "t_mean_comp", "precipitation")) # 2. Monthly absolute anomalies (default) anom <- sus_climate_anomaly(obs, norm) # 3. Standardized anomalies for multi-city DLNM pooling anom_std <- sus_climate_anomaly(obs, norm, method = "standardized", vars = c(tair_dry_bulb_c = "t_mean_comp")) # 4. Decadal precipitation anomalies — dengue/leptospirosis lag studies anom_10d <- sus_climate_anomaly(obs, norm, method = "relative", time_scale = "decadal", vars = c(rainfall_mm = "precipitation")) # 5. All methods at once — exploratory anom_all <- sus_climate_anomaly(obs, norm, method = "all") ## End(Not run)## Not run: # 1. Download data obs <- sus_climate_inmet(years = 2018:2023, uf = "RJ") norm <- sus_climate_normals(period = "1991-2020", target_var = c("t_max", "t_min", "t_mean_comp", "precipitation")) # 2. Monthly absolute anomalies (default) anom <- sus_climate_anomaly(obs, norm) # 3. Standardized anomalies for multi-city DLNM pooling anom_std <- sus_climate_anomaly(obs, norm, method = "standardized", vars = c(tair_dry_bulb_c = "t_mean_comp")) # 4. Decadal precipitation anomalies — dengue/leptospirosis lag studies anom_10d <- sus_climate_anomaly(obs, norm, method = "relative", time_scale = "decadal", vars = c(rainfall_mm = "precipitation")) # 5. All methods at once — exploratory anom_all <- sus_climate_anomaly(obs, norm, method = "all") ## End(Not run)
Applies seven coldwave detection methods (WHO, WMO, INMET, ECF, UTCI, WBGT,
HI) to a climasus_df at stage "climate" produced by
sus_climate_inmet(), sus_climate_fill_gap(), or
sus_climate_compute_indicators(). Aggregates hourly data to daily scale,
computes smoothed historical percentile thresholds from a reference baseline,
identifies coldwave days and discrete events per method, and returns a named
list with events, daily-flag, and annual-summary tables — all carrying
sus_meta at stage "climate" / type "coldwaves".
sus_climate_compute_coldwaves( df, method = c("WHO", "WMO", "INMET", "EHF", "UTCI", "WBGT", "HI"), baseline_start = NULL, baseline_end = NULL, percentile = 10, min_duration = NULL, lang = "pt", verbose = TRUE )sus_climate_compute_coldwaves( df, method = c("WHO", "WMO", "INMET", "EHF", "UTCI", "WBGT", "HI"), baseline_start = NULL, baseline_end = NULL, percentile = 10, min_duration = NULL, lang = "pt", verbose = TRUE )
df |
A |
method |
Character vector. One or more of |
baseline_start |
Date or character (e.g., |
baseline_end |
Date or character. End of the reference period.
|
percentile |
Numeric (0-100, default |
min_duration |
Integer or |
lang |
Character. Output language: |
verbose |
Logical. Print progress messages. Default |
A named list with class climasus_cw and sus_meta attribute
(stage "climate", type "coldwaves"):
eventsOne row per detected event: event_id, station_code,
method, start_date, end_date, duration_days, temp_mean,
temp_peak (coldest), anomaly_mean, anomaly_cumulative,
severity_index, ecf_peak, ecf_mean, intensity_class, and
station metadata.
dailyDaily aggregated data with logical flag columns
cw_<method> and cw_any.
summaryAnnual summary by station and method: year,
n_events, total_days_cw, mean_duration, max_duration,
mean_intensity, max_intensity, mean_anomaly, severity_total.
1. WHO Tmin < P10(Tmin) for >= N consecutive days (default N=3).
Threshold smoothed over a 15-day rolling window by calendar day-of-year.
Reference: WMO & WHO (2015).
2. WMO Tmin < P10(Tmin) AND Tmax < P10(Tmax) for >= N days (default
N=5). Double threshold ensures both daytime and nighttime extremes are
captured. Reference: Perkins & Alexander (2013).
3. INMET Tmin < mean(Tmin_hist) - 5 degC for >= N days (default N=5).
Climatological mean from the baseline period. Designed for Brazilian context.
4. ECF Excess Cold Factor: ECF = ECI_sig x max(1, ECI_acc) where
ECI_sig = P5(Tmean) - T3 and ECI_acc = T30 - T3. Intensity classified
by ECF85 (85th percentile of positive ECF values). Adaptation of Nairn &
Fawcett (2015) for cold extremes. Positive ECI_acc means the preceding
month was warmer than the recent 3-day mean (body acclimatised to heat,
amplifying cold stress).
5. UTCI UTCImin < P10(UTCImin) for >= N days (default N=3). Requires
utci_c column from sus_climate_compute_indicators().
6. WBGT WBGTmin < P10(WBGTmin) for >= N days (default N=3). Requires
wbgt_c column from sus_climate_compute_indicators().
7. HI HImin < P10(HImin) for >= N days (default N=3). Requires hi_c
column from sus_climate_compute_indicators().
Perkins, S.E. & Alexander, L.V. (2013). On the measurement of heat waves. Journal of Climate, 26(13), 4500-4517. (Adapted for coldwaves)
WMO & WHO (2015). Heatwaves and Health: Guidance on Warning-System Development. Geneva. (Adapted for coldwaves)
Nairn, J.R. & Fawcett, R.J.B. (2015). The Excess Heat Factor. Int. J. Environ. Res. Public Health, 12(1), 227-253. (Adapted for cold) doi:10.3390/ijerph120100227
INMET (2009). Normais Climatologicas do Brasil 1961-1990. Brasilia.
sus_climate_inmet(), sus_climate_compute_indicators(),
sus_climate_plot_coldwaves()
## Not run: cw <- df_indicators |> sus_climate_compute_coldwaves( method = c("WHO", "INMET", "EHF"), baseline_start = "2000-01-01", baseline_end = "2020-12-31", lang = "pt" ) cw$events cw$summary cw$daily[cw$daily$cw_any, ] ## End(Not run)## Not run: cw <- df_indicators |> sus_climate_compute_coldwaves( method = c("WHO", "INMET", "EHF"), baseline_start = "2000-01-01", baseline_end = "2020-12-31", lang = "pt" ) cw$events cw$summary cw$daily[cw$daily$cw_any, ] ## End(Not run)
Applies seven heatwave detection methods (WHO, WMO, INMET, EHF, UTCI, WBGT,
HI) to a climasus_df at stage "climate" produced by
sus_climate_inmet(), sus_climate_fill_gap(), or
sus_climate_compute_indicators(). Aggregates hourly data to daily scale,
computes smoothed historical percentile thresholds from a reference baseline,
identifies heatwave days and discrete events per method, and returns a named
list with event, daily-flag, and annual-summary tables — all carrying
sus_meta at stage "climate" / type "heatwaves".
sus_climate_compute_heatwaves( df, method = c("WHO", "WMO", "INMET", "EHF", "UTCI", "WBGT", "HI"), baseline_start = NULL, baseline_end = NULL, percentile = 90, min_duration = NULL, lang = "pt", verbose = TRUE )sus_climate_compute_heatwaves( df, method = c("WHO", "WMO", "INMET", "EHF", "UTCI", "WBGT", "HI"), baseline_start = NULL, baseline_end = NULL, percentile = 90, min_duration = NULL, lang = "pt", verbose = TRUE )
df |
A |
method |
Character vector. One or more of |
baseline_start |
Date or character (e.g., |
baseline_end |
Date or character. End of the reference period.
|
percentile |
Numeric (0–100, default |
min_duration |
Integer or |
lang |
Character. Output language: |
verbose |
Logical. Print progress messages. Default |
A named list with class climasus_hw and sus_meta attribute
(stage "climate", type "heatwaves"):
eventsOne row per detected event: event_id, station_code,
method, start_date, end_date, duration_days, temp_mean,
temp_peak, anomaly_mean, anomaly_cumulative, severity_index,
ehf_peak, ehf_mean, intensity_class, and station metadata.
dailyDaily aggregated data with logical flag columns
hw_<method> and hw_any.
summaryAnnual summary by station and method: year,
n_events, total_days_hw, mean_duration, max_duration,
mean_intensity, max_intensity, mean_anomaly, severity_total.
1. WHO Tmax > P90(Tmax) for >= N consecutive days (default N=3).
Threshold smoothed over a 15-day rolling window by calendar day-of-year.
Reference: WMO & WHO (2015).
2. WMO Tmax > P90(Tmax) AND Tmin > P90(Tmin) for >= N days (default
N=5). Double threshold ensures both daytime and nighttime extremes are
captured. Reference: Perkins & Alexander (2013).
3. INMET Tmax > mean(Tmax_hist) + 5 degC for >= N days (default N=5).
Climatological mean from the baseline period. Designed for Brazilian context.
Reference: INMET (2009); MCTI/Gov.br (2025).
4. EHF Excess Heat Factor: EHF = EHI_sig x max(1, EHI_acc) where
EHI_sig = T3 - P95(Tmean) and EHI_acc = T3 - T30. Intensity classified
by EHF85 (85th percentile of positive EHF values). Reference: Nairn &
Fawcett (2015).
5. UTCI UTCImax > P90(UTCImax) for >= N days (default N=3). Requires
utci_c column from sus_climate_compute_indicators().
6. WBGT WBGTmax > P90(WBGTmax) for >= N days (default N=3). Requires
wbgt_c column from sus_climate_compute_indicators().
7. HI HImax > P90(HImax) for >= N days (default N=3). Requires hi_c
column from sus_climate_compute_indicators().
Perkins, S.E. & Alexander, L.V. (2013). On the measurement of heat waves. Journal of Climate, 26(13), 4500-4517.
WMO & WHO (2015). Heatwaves and Health: Guidance on Warning-System Development. Geneva.
Nairn, J.R. & Fawcett, R.J.B. (2015). The Excess Heat Factor. Int. J. Environ. Res. Public Health, 12(1), 227-253. doi:10.3390/ijerph120100227
Broede, P. et al. (2012). Deriving the operational procedure for UTCI. Int. J. Biometeorology, 56(3), 481-494. doi:10.1007/s00484-011-0454-1
INMET (2009). Normais Climatologicas do Brasil 1961-1990. Brasilia.
sus_climate_inmet(), sus_climate_compute_indicators()
## Not run: hw <- df_indicators |> sus_climate_compute_heatwaves( method = c("WHO", "INMET", "EHF"), baseline_start = "2000-01-01", baseline_end = "2020-12-31", lang = "pt" ) hw$events hw$summary hw$daily[hw$daily$hw_any, ] ## End(Not run)## Not run: hw <- df_indicators |> sus_climate_compute_heatwaves( method = c("WHO", "INMET", "EHF"), baseline_start = "2000-01-01", baseline_end = "2020-12-31", lang = "pt" ) hw$events hw$summary hw$daily[hw$daily$hw_any, ] ## End(Not run)
sus_climate_compute_indicators() calculates a comprehensive set of
bioclimatic and thermal-stress indices from INMET station data (output of
sus_climate_inmet() or sus_climate_fill_inmet()).
Scientific robustness highlights:
WBGT uses a dual wet-bulb estimate (Liljegren + Bernard/Pourmoghani)
averaged for numerical robustness; solar radiation NA treated as 0
(no solar load at night) so all hours yield a valid value.
HI implements full Rothfusz (1990) regression with both NWS humidity adjustments and a regionally adapted validity threshold.
UTCI uses a Fiala-polynomial-inspired multi-term regression (vapour pressure, logarithmic wind, radiation linear + non-linear, wind vs radiation interaction).
PET is based on a MEMI-style energy-balance approximation with seasonal clothing adjustment and regional correction.
Solar radiation undergoes optional physical consistency verification against extraterrestrial radiation limits.
Diurnal range is a true daily aggregate (Tmax - Tmin per calendar day) broadcast to all hourly rows of that day.
Multi-level confidence flags (_flag_extreme, _flag_high,
_flag_low) replace a single _out_of_range flag.
Optional 200-simulation Monte Carlo uncertainty estimation.
Available indicators:
| Code | Output column | Requires |
wbgt |
wbgt_c |
T, RH, SR, WS |
hi |
hi_c |
T, RH |
thi |
thi_c |
T, RH |
wcet |
wcet_c |
T, WS |
wct |
wct_c |
T, WS |
et |
et_c |
T, RH, WS |
utci |
utci_c |
T, RH, WS, SR |
pet |
pet_c |
T, RH, WS, SR |
cdd |
cdd_c |
T |
hdd |
hdd_c |
T |
gdd |
gdd_c |
T |
diurnal_range |
diurnal_range_c |
T (daily agg.) |
vapor_pressure |
vapor_pressure_kpa |
T, RH |
heat_stress_risk |
heat_stress_risk |
T, RH, WS, SR |
koppen_humidity |
koppen_humidity |
RH |
(Where: T=tair_dry_bulb_c, RH=rh_mean_porc, SR=sr_kj_m2, WS=ws_2_m_s)
sus_climate_compute_indicators( df, indicators = "all", region = "auto", datetime_col = NULL, station_col = NULL, apply_validity_mask = TRUE, confidence_flags = NULL, custom_thresholds = NULL, keep_source_vars = FALSE, verify_physics = TRUE, compute_uncertainty = FALSE, verbose = TRUE, lang = "pt", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial" )sus_climate_compute_indicators( df, indicators = "all", region = "auto", datetime_col = NULL, station_col = NULL, apply_validity_mask = TRUE, confidence_flags = NULL, custom_thresholds = NULL, keep_source_vars = FALSE, verify_physics = TRUE, compute_uncertainty = FALSE, verbose = TRUE, lang = "pt", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial" )
df |
Data frame or tibble from |
indicators |
Character vector of indicator codes or |
region |
Character. |
datetime_col |
Character or |
station_col |
Character or |
apply_validity_mask |
Logical (default |
confidence_flags |
Logical. Add |
custom_thresholds |
Named list to override regional defaults. |
keep_source_vars |
Logical (default |
verify_physics |
Logical (default |
compute_uncertainty |
Logical (default |
verbose |
Logical (default |
lang |
Character: |
use_cache |
Logical. If |
cache_dir |
Character string specifying the directory to store cached files.
Default is |
A tibble of class climasus_df containing indicator columns,
optional flag/CI columns, and a sus_meta attribute.
Liljegren et al. (2008) J. Occup. Environ. Hyg. 5(10):645-655.
Bernard & Pourmoghani (1999) AIHAJ 60(1):32-37.
Rothfusz (1990) NWS Tech. Attachment SR/SSD 90-23.
Thom (1959) Weatherwise 12(2):57-59.
Environment Canada (2001) Wind Chill Index.
Brode et al. (2012) Int. J. Biometeorol. 56(4):481-494.
Matzarakis et al. (1999) Int. J. Biometeorol. 43:76-84.
Magnus (1844) / Tetens (1930) saturation vapour pressure.
## Not run: result <- sus_climate_compute_indicators(df_clima) result <- sus_climate_compute_indicators( df_clima, region = "amazon", confidence_flags = TRUE ) result <- sus_climate_compute_indicators( df_clima, region = "auto", verify_physics = TRUE, compute_uncertainty = TRUE, keep_source_vars = TRUE ) df_clima |> sus_climate_fill_inmet(target_var = "all") |> sus_climate_compute_indicators(indicators = c("wbgt", "hi", "utci")) ## End(Not run)## Not run: result <- sus_climate_compute_indicators(df_clima) result <- sus_climate_compute_indicators( df_clima, region = "amazon", confidence_flags = TRUE ) result <- sus_climate_compute_indicators( df_clima, region = "auto", verify_physics = TRUE, compute_uncertainty = TRUE, keep_source_vars = TRUE ) df_clima |> sus_climate_fill_inmet(target_var = "all") |> sus_climate_compute_indicators(indicators = c("wbgt", "hi", "utci")) ## End(Not run)
sus_climate_compute_spei() calculates the Standardized Precipitation-
Evapotranspiration Index (SPEI; Vicente-Serrano et al., 2010) at multiple
timescales from monthly precipitation and potential evapotranspiration (PET)
already aggregated to municipalities.
SPEI extends sus_climate_compute_spi() by accounting for atmospheric water
demand (temperature-driven evapotranspiration) in addition to precipitation
supply. It uses the climatic water balance D = P - PET and fits a
3-parameter log-logistic distribution, making it sensitive to warming-
amplified drought. Health applications in Brazil:
Drought (SPEI-3 to SPEI-12): malnutrition, diarrhoeal disease, heat-amplified mortality, vector-borne diseases in the semi-arid Northeast and Amazônia
Wet spells (positive SPEI): leptospirosis, hepatitis A, dengue
PET options (choose one):
pet_method = "column" (default): pass a pre-computed PET column
via pet_var. ERA5-Land potential evapotranspiration ("evap") or the
FAO Penman-Monteith result are ideal.
pet_method = "thornthwaite": compute PET internally using only
monthly mean temperature (temp_var). Suitable when only temperature
data is available (e.g., INMET or ERA5 T2m).
sus_climate_compute_spei( df, rain_var = "rainfall_chirps_mm", pet_var = "pet_mm", pet_method = c("column", "thornthwaite"), temp_var = "tair_dry_bulb_c", scales = c(1L, 3L, 6L, 12L), ref_start = NULL, ref_end = NULL, min_n = 24L, lang = "pt", verbose = TRUE )sus_climate_compute_spei( df, rain_var = "rainfall_chirps_mm", pet_var = "pet_mm", pet_method = c("column", "thornthwaite"), temp_var = "tair_dry_bulb_c", scales = c(1L, 3L, 6L, 12L), ref_start = NULL, ref_end = NULL, min_n = 24L, lang = "pt", verbose = TRUE )
df |
A |
rain_var |
Character. Name of the monthly precipitation column (mm).
Default |
pet_var |
Character. Name of the monthly potential evapotranspiration
column (mm). Used when |
pet_method |
Character. How to obtain PET values. One of:
|
temp_var |
Character. Name of the monthly mean temperature column (°C).
Used only when |
scales |
Integer vector. SPEI timescales in months. Default
|
ref_start |
Date or |
ref_end |
Date or |
min_n |
Integer. Minimum number of non-NA values required to fit the
log-logistic distribution per location. Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
The input climasus_df with additional columns:
spei_{s}mo — SPEI at timescale s months (numeric,
dimensionless). For example, scales = c(3, 6, 12) adds
spei_3mo, spei_6mo, spei_12mo.
Metadata: stage = "climate", type = "spei".
SPEI is more sensitive to climate change because rising temperatures increase PET even when precipitation is unchanged. Use SPEI-3 for short-term drought and health outcomes with 1-4 week lag (diarrhoea, dengue). Use SPEI-6 or SPEI-12 for water supply and agricultural drought (malnutrition, livelihood loss).
For each municipality and timescale s:
Compute climate water balance: D = P - PET (monthly).
Accumulate over s months via rolling sum.
Fit 3-parameter log-logistic distribution via L-moments (Vicente-Serrano et al., 2010). Falls back to empirical ECDF for numerically unstable cases.
Transform to standard normal.
Vicente-Serrano, S.M., Beguería, S., López-Moreno, J.I. (2010). A multiscalar drought index sensitive to global warming: the Standardized Precipitation Evapotranspiration Index. Journal of Climate, 23(7), 1696–1718. doi:10.1175/2009JCLI2909.1
Thornthwaite, C.W. (1948). An approach toward a rational classification of climate. Geographical Review, 38(1), 55–94.
sus_climate_compute_spi(), sus_grid_chirps(), sus_grid_era5(),
sus_grid_join(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Option A: SPEI from CHIRPS + Thornthwaite PET (ERA5-Land temperature) chirps_era5 <- sus_grid_era5( years = 1990:2022, vars = c("t2m"), municipalities = mt_mun ) |> sus_grid_join( sus_grid_chirps(resolution="monthly", years=1990:2022, municipalities=mt_mun) ) spei_mt <- sus_climate_compute_spei( df = chirps_era5, rain_var = "rainfall_chirps_mm", pet_method = "thornthwaite", temp_var = "tair_dry_bulb_c", scales = c(3L, 6L, 12L), lang = "pt" ) # Option B: SPEI from pre-computed PET column spei_mt2 <- sus_climate_compute_spei( df = climate_df, # has rainfall_mm and pet_mm columns rain_var = "rainfall_mm", pet_var = "pet_mm", pet_method = "column", scales = c(3L, 6L, 12L) ) sus_meta(spei_mt, "stage") # "climate" sus_meta(spei_mt, "type") # "spei" names(spei_mt) # ..., spei_3mo, spei_6mo, spei_12mo ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Option A: SPEI from CHIRPS + Thornthwaite PET (ERA5-Land temperature) chirps_era5 <- sus_grid_era5( years = 1990:2022, vars = c("t2m"), municipalities = mt_mun ) |> sus_grid_join( sus_grid_chirps(resolution="monthly", years=1990:2022, municipalities=mt_mun) ) spei_mt <- sus_climate_compute_spei( df = chirps_era5, rain_var = "rainfall_chirps_mm", pet_method = "thornthwaite", temp_var = "tair_dry_bulb_c", scales = c(3L, 6L, 12L), lang = "pt" ) # Option B: SPEI from pre-computed PET column spei_mt2 <- sus_climate_compute_spei( df = climate_df, # has rainfall_mm and pet_mm columns rain_var = "rainfall_mm", pet_var = "pet_mm", pet_method = "column", scales = c(3L, 6L, 12L) ) sus_meta(spei_mt, "stage") # "climate" sus_meta(spei_mt, "type") # "spei" names(spei_mt) # ..., spei_3mo, spei_6mo, spei_12mo ## End(Not run)
sus_climate_compute_spi() calculates the Standardized Precipitation Index
(SPI; McKee et al., 1993) at multiple timescales from monthly cumulative
precipitation already aggregated to municipalities.
SPI is a dimensionless index of precipitation anomaly relative to a
long-term distribution: negative values indicate drought (SPI
-1 = moderate, -1.5 = severe, -2 = extreme) and
positive values indicate wet conditions. Multi-scale SPI is a leading
indicator for several health outcomes in Brazil:
Drought (SPI-3, SPI-6): diarrhoeal disease, malnutrition, vector-borne diseases during water scarcity
Wet spells (SPI-1, SPI-3): leptospirosis, hepatitis A, dengue
The function requires monthly precipitation data (one row per
municipality × month). The best upstream source is
sus_grid_chirps() with resolution = "monthly" (0.05°, 1981–present).
INMET-derived rainfall_mm from sus_climate_aggregate() also works.
sus_climate_compute_spi( df, var = "rainfall_chirps_mm", scales = c(1L, 3L, 6L, 12L), ref_start = NULL, ref_end = NULL, min_n = 24L, lang = "pt", verbose = TRUE )sus_climate_compute_spi( df, var = "rainfall_chirps_mm", scales = c(1L, 3L, 6L, 12L), ref_start = NULL, ref_end = NULL, min_n = 24L, lang = "pt", verbose = TRUE )
df |
A |
var |
Character. Name of the monthly precipitation column.
Default |
scales |
Integer vector. SPI timescales in months. Default
|
ref_start |
Date or |
ref_end |
Date or |
min_n |
Integer. Minimum number of non-NA, non-zero precipitation
values required to fit the gamma distribution per location. Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
The input climasus_df with additional columns:
spi_{s}mo — SPI at timescale s months (numeric, dimensionless)
For example, scales = c(1, 3, 6, 12) adds spi_1mo, spi_3mo,
spi_6mo, spi_12mo. Metadata: stage = "climate", type = "spi".
SPI ≥ 2.0 : Extremely wet SPI 1.5 to 1.99 : Very wet SPI 1.0 to 1.49 : Moderately wet SPI -0.99 to 0.99 : Near normal SPI -1.0 to -1.49 : Moderately dry (D1) SPI -1.5 to -1.99 : Severely dry (D2) SPI ≤ -2.0 : Extremely dry (D3-D4)
For each municipality and timescale s:
Compute s-month rolling sum of precipitation using
slider::slide_dbl().
Estimate gamma distribution parameters (shape ,
rate ) via method of moments from the calibration period,
handling zero-inflation with a mixed distribution (McKee et al., 1993).
Transform to standard normal: SPI = qnorm(p0 + (1-p0) * pgamma(x, shape, rate)), where p0 is the proportion of zeros.
McKee, T.B., Doesken, N.J., Kleist, J. (1993). The relationship of drought frequency and duration to time scales. Proceedings of the 8th Conference on Applied Climatology. American Meteorological Society.
sus_grid_chirps(), sus_climate_anomaly(), sus_grid_join(),
sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Download monthly CHIRPS for Mato Grosso, 1990-2022 chirps_mt <- sus_grid_chirps( resolution = "monthly", years = 1990:2022, municipalities = mt_mun ) # Compute SPI at 1-, 3-, 6- and 12-month timescales spi_mt <- sus_climate_compute_spi( df = chirps_mt, var = "rainfall_chirps_mm", scales = c(1L, 3L, 6L, 12L), ref_start = as.Date("1991-01-01"), ref_end = as.Date("2020-12-31"), lang = "pt" ) sus_meta(spi_mt, "stage") # "climate" sus_meta(spi_mt, "type") # "spi" names(spi_mt) # ..., spi_1mo, spi_3mo, spi_6mo, spi_12mo # Join to health data combined <- sus_grid_join(health_mt, spi_mt) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Download monthly CHIRPS for Mato Grosso, 1990-2022 chirps_mt <- sus_grid_chirps( resolution = "monthly", years = 1990:2022, municipalities = mt_mun ) # Compute SPI at 1-, 3-, 6- and 12-month timescales spi_mt <- sus_climate_compute_spi( df = chirps_mt, var = "rainfall_chirps_mm", scales = c(1L, 3L, 6L, 12L), ref_start = as.Date("1991-01-01"), ref_end = as.Date("2020-12-31"), lang = "pt" ) sus_meta(spi_mt, "stage") # "climate" sus_meta(spi_mt, "type") # "spi" names(spi_mt) # ..., spi_1mo, spi_3mo, spi_6mo, spi_12mo # Join to health data combined <- sus_grid_join(health_mt, spi_mt) ## End(Not run)
sus_climate_fill_inmet() imputes missing values in INMET automatic station data
using station-wise XGBoost models with automated feature engineering.
Key features:
Multi-target support: Impute one, many, or ALL numeric variables in a single call
Station-wise modeling: Separate model per station per variable
Temporal features: Automatic creation of lags and rolling statistics
Quality control: Stations with >quality_threshold missing are excluded
Parallel processing: Stations processed in parallel; workers resolved once and reused across all variable iterations
Evaluation mode: Assess accuracy by creating artificial gaps
Important: This function is designed exclusively for data imported by
sus_climate_inmet() and works with the standard INMET variable set.
sus_climate_fill_inmet( df, target_var, datetime_col = NULL, station_col = NULL, quality_threshold = 0.4, run_evaluation = FALSE, gap_percentage = 0.2, keep_features = FALSE, parallel = TRUE, workers = NULL, verbose = TRUE, lang = "pt" )sus_climate_fill_inmet( df, target_var, datetime_col = NULL, station_col = NULL, quality_threshold = 0.4, run_evaluation = FALSE, gap_percentage = 0.2, keep_features = FALSE, parallel = TRUE, workers = NULL, verbose = TRUE, lang = "pt" )
df |
A data frame (or tibble) containing climate data, typically from
|
target_var |
Character vector of column name(s) to impute, or the special string
|
datetime_col |
Character. Name of the datetime column. If |
station_col |
Character. Name of the station identifier column. If |
quality_threshold |
Numeric (0-1). Maximum allowed missing proportion per station.
Stations exceeding this are excluded. Default: For INMET data: Recommended values:
|
run_evaluation |
Logical. If
Default: |
gap_percentage |
Numeric (0-1). Proportion of data to set as missing in evaluation mode. The |
keep_features |
Logical. If |
parallel |
Logical. If |
workers |
Integer. Number of parallel workers. If |
verbose |
Logical. If |
lang |
Character. Message language: |
Production mode (run_evaluation = FALSE):
Single variable: a tibble (same class as input) with imputed values in
target_var and an is_imputed_<var> flag column.
Multiple variables / "all": the same tibble with all requested variables
imputed sequentially, each with its own is_imputed_<var> flag column.
A sus_meta attribute records all imputed variables and their rates.
Evaluation mode (run_evaluation = TRUE):
Returns a named list (one element per variable) of class climasus_eval, each with:
$data: Data frame with artificial gaps and predictions
$metrics: A tibble with per-station performance metrics:
station: Station identifier
rmse: Root Mean Squared Error
mae: Mean Absolute Error
r_squared: R-squared (lower than 1, higher is better)
smape: Symmetric MAPE (0-200%, lower is better)
slope_bias: Should be close to 1.0, indicating underestimate and overestimate
n_gaps: Number of artificial gaps
The function is optimized for the following 17 INMET variables:
Atmospheric Pressure: patm_mb, patm_max_mb, patm_min_mb
Temperature: tair_dry_bulb_c, tair_max_c, tair_min_c
Dew Point: dew_tmean_c, dew_tmax_c, dew_tmin_c
Relative Humidity: rh_max_porc, rh_min_porc, rh_mean_porc
Precipitation: rainfall_mm
Wind: ws_gust_m_s, ws_2_m_s, wd_degrees
Solar Radiation: sr_kj_m2
When target_var = "all", the function automatically detects and imputes
only these 17 variables if present in the data.
Important limitations:
Not forecasting: Predicts only where data are missing
No future data: Uses only past information (lags)
Station independence: Models don't share information
Quality filter: Stations with >quality_threshold missing are skipped
Feature engineering: Automatically creates:
Time features: hour, day, month, year, cyclic transforms
Lag features: 1,2,3,6,12,24,48,72,168 periods
Rolling statistics: mean and sd over windows 3,6,12,24,48,72
When run_evaluation = TRUE, the function:
Creates artificial gaps (MCAR by default)
Runs imputation on the data with gaps
Compares predictions with true values
Returns per-station performance
This helps assess model accuracy before production use.
## Not run: # ===== PRODUCTION MODE — single variable ===== filled_temp <- sus_climate_fill_inmet( df = climate_data, target_var = "tair_dry_bulb_c", quality_threshold = 0.3, parallel = TRUE ) # ===== PRODUCTION MODE — multiple variables ===== filled_multi <- sus_climate_fill_inmet( df = climate_data, target_var = c("tair_dry_bulb_c", "rh_pct", "ws_2_m_s"), quality_threshold = 0.3, parallel = TRUE, workers = 4 ) # ===== PRODUCTION MODE — all numeric variables ===== filled_all <- sus_climate_fill_inmet( df = climate_data, target_var = "all", parallel = TRUE ) # ===== EVALUATION MODE — single variable ===== eval_results <- sus_climate_fill_inmet( df = climate_data, target_var = "ws_2_m_s", run_evaluation = TRUE, gap_percentage = 0.2, workers = 4 ) eval_results$ws_2_m_s$metrics # ===== EVALUATION MODE — multiple variables ===== eval_multi <- sus_climate_fill_inmet( df = climate_data, target_var = c("tair_dry_bulb_c", "ws_2_m_s"), run_evaluation = TRUE, gap_percentage = 0.2 ) eval_multi$tair_dry_bulb_c$metrics eval_multi$ws_2_m_s$metrics ## End(Not run)## Not run: # ===== PRODUCTION MODE — single variable ===== filled_temp <- sus_climate_fill_inmet( df = climate_data, target_var = "tair_dry_bulb_c", quality_threshold = 0.3, parallel = TRUE ) # ===== PRODUCTION MODE — multiple variables ===== filled_multi <- sus_climate_fill_inmet( df = climate_data, target_var = c("tair_dry_bulb_c", "rh_pct", "ws_2_m_s"), quality_threshold = 0.3, parallel = TRUE, workers = 4 ) # ===== PRODUCTION MODE — all numeric variables ===== filled_all <- sus_climate_fill_inmet( df = climate_data, target_var = "all", parallel = TRUE ) # ===== EVALUATION MODE — single variable ===== eval_results <- sus_climate_fill_inmet( df = climate_data, target_var = "ws_2_m_s", run_evaluation = TRUE, gap_percentage = 0.2, workers = 4 ) eval_results$ws_2_m_s$metrics # ===== EVALUATION MODE — multiple variables ===== eval_multi <- sus_climate_fill_inmet( df = climate_data, target_var = c("tair_dry_bulb_c", "ws_2_m_s"), run_evaluation = TRUE, gap_percentage = 0.2 ) eval_multi$tair_dry_bulb_c$metrics eval_multi$ws_2_m_s$metrics ## End(Not run)
sus_climate_inmet() downloads, imports, standardizes, and quality-controls
Brazilian meteorological data from the National Institute of Meteorology (INMET).
The function implements a comprehensive processing pipeline:
Download: Multi-year data with automatic retry and backoff
Parsing: Handles INMET's CSV format with metadata extraction
Standardization: Renames columns to canonical names (see Variables)
Quality Control: Physical consistency checks (see QC Details)
Caching: Two-level (memory + disk) with Parquet format
Parallel Processing: Both between and within years
sus_climate_inmet( years = NULL, uf = NULL, station_code = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/climate", parallel = TRUE, workers = 4, lang = "pt", verbose = TRUE )sus_climate_inmet( years = NULL, uf = NULL, station_code = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/climate", parallel = TRUE, workers = 4, lang = "pt", verbose = TRUE )
years |
Numeric vector of year(s) to import.
Examples: |
uf |
Character vector of Brazilian state codes (e.g., |
station_code |
Character vector of INMET station codes to filter
(e.g., |
use_cache |
Logical. If
Use |
cache_dir |
Character. Directory path for disk cache.
Default: |
parallel |
Logical. If
For single-year imports, only within-year parallelization applies. |
workers |
Integer. Number of parallel workers. Default: |
lang |
Character. Message language. One of:
|
verbose |
Logical. If
|
A climasus_df object (subclass of tibble) with class hierarchy:
climasus_df > tbl_df > tbl > data.frame
Data Columns:
station_codeCharacter. INMET 8-digit station identifier (e.g., "A001")
station_nameCharacter. Full station name
regionCharacter. Brazilian region (Norte, Nordeste, etc.)
UFCharacter. State abbreviation
latitude, longitude, altitude
Numeric. Station coordinates (WGS84)
datePOSIXct. Observation timestamp UTC (always hourly)
yearInteger. Year extracted from date
Numeric. Standardized names (see Variables)
Metadata (accessible via attr(x, "sus_meta")):
versionPackage version used
timestampImport date/time
source"INMET"
yearsYears imported
ufsStates imported
station_codesStation codes filtered (or NULL if all)
cache_usedWhether cache was used
qc_statsList with quality control statistics
n_stationsNumber of unique stations
n_observationsTotal rows
temporal_coverageList with start and end dates
historyCharacter vector of processing steps
INMET raw column names vary by year. This function automatically detects and renames them to the following canonical names:
| Canonical Name | Description | Unit | Physical Range |
rainfall_mm |
Precipitation total | mm | 0 - 500 |
patm_mb |
Mean atmospheric pressure | mb | 700 - 1100 |
patm_max_mb |
Max atmospheric pressure | mb | 700 - 1100 |
patm_min_mb |
Min atmospheric pressure | mb | 700 - 1100 |
sr_kj_m2 |
Solar radiation | kJ/m² | 0 - 40000 |
tair_dry_bulb_c |
Mean air temperature | °C | -90 - 60 |
tair_max_c |
Max air temperature | °C | -90 - 60 |
tair_min_c |
Min air temperature | °C | -90 - 60 |
dew_tmean_c |
Mean dew point | °C | -90 - 60 |
dew_tmax_c |
Max dew point | °C | -90 - 60 |
dew_tmin_c |
Min dew point | °C | -90 - 60 |
rh_mean_porc |
Mean relative humidity | % | 0 - 100 |
rh_max_porc |
Max relative humidity | % | 0 - 100 |
rh_min_porc |
Min relative humidity | % | 0 - 100 |
ws_2_m_s |
Wind speed at 2m | m/s | 0 - 100 |
ws_gust_m_s |
Wind gust | m/s | 0 - 100 |
wd_degrees |
Wind direction | degrees | 0 - 360 |
The function applies automatic physical consistency checks:
1. Physical Range Validation:
Values outside physically possible ranges are set to NA:
Temperature: -90°C to 60°C
Pressure: 700 mb to 1100 mb
Humidity: 0% to 100%
Precipitation: 0 mm to 500 mm
Solar radiation: 0 to 40000 kJ/m²
Wind speed: 0 to 100 m/s
Wind direction: 0° to 360°
2. Dew Point Consistency: Calculates theoretical dew point from T and RH using Magnus formula. If |observed - calculated| > 3°C, observed is set to NA.
3. Solar Radiation: Nighttime values (18h-6h) are set to 0 for physical consistency.
Disk Cache:
Format: Apache Parquet with Zstandard compression (level 6)
Partitioning: By year and UF for fast filtering
Backup: Compressed CSV as fallback if Parquet corrupted
Location: ~/.climasus4r_cache/climate/inmet_parquet/
Data frequency: Always hourly. Use sus_climate_aggregate() for daily/weekly.
Timezone: All timestamps are UTC. Convert if needed.
Missing data: Represented as NA. Use sus_climate_fill_inmet() for imputation.
Encoding: All strings converted to UTF-8.
Decimals: Converted from comma (,) to point (.).
sus_climate_fill_inmet() for ML-based gap filling
sus_spatial_join() for preparing municipality data
## Not run: # Basic import - single state, single year climate_am <- sus_climate_inmet( years = 2023, uf = "AM" ) # Filter by specific station codes climate_sp <- sus_climate_inmet( years = 2023, uf = "SP", station_code = c("A701", "A711") ) # Multi-year import with parallel processing climate_sp <- sus_climate_inmet( years = 2020:2024, uf = "SP", parallel = TRUE, workers = 4 ) # Import all Southeast states climate_se <- sus_climate_inmet( years = 2023, uf = c("SP", "RJ", "MG", "ES"), verbose = TRUE ) # Inspect available stations climate_df |> dplyr::distinct(station_code, station_name, latitude, longitude) ## End(Not run)## Not run: # Basic import - single state, single year climate_am <- sus_climate_inmet( years = 2023, uf = "AM" ) # Filter by specific station codes climate_sp <- sus_climate_inmet( years = 2023, uf = "SP", station_code = c("A701", "A711") ) # Multi-year import with parallel processing climate_sp <- sus_climate_inmet( years = 2020:2024, uf = "SP", parallel = TRUE, workers = 4 ) # Import all Southeast states climate_se <- sus_climate_inmet( years = 2023, uf = c("SP", "RJ", "MG", "ES"), verbose = TRUE ) # Inspect available stations climate_df |> dplyr::distinct(station_code, station_name, latitude, longitude) ## End(Not run)
sus_climate_normals() retrieves 30-year climatological normals from the
Brazilian National Institute of Meteorology (INMET) for one of three
reference periods (1961-1990, 1981-2010, 1991-2020). It loads the variable
catalogue from the bundled normal_meta.parquet dictionary—with transparent
disk caching and automatic fallback download—then fetches each selected
variable's Excel file from the INMET portal, parses the decade-level monthly
structure, and returns a tidy long-format climasus_df.
sus_climate_normals( period = "1991-2020", target_var = NULL, cache_dir = "~/.climasus4r_cache/normals", use_cache = TRUE, lang = "pt", verbose = TRUE )sus_climate_normals( period = "1991-2020", target_var = NULL, cache_dir = "~/.climasus4r_cache/normals", use_cache = TRUE, lang = "pt", verbose = TRUE )
period |
Character. Reference climatological period. One of
|
target_var |
Character vector of |
cache_dir |
Character. Local directory for disk-cached files.
Default: |
use_cache |
Logical. If |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
A climasus_df object at stage "climate" and type "normals",
tidy long format with columns:
codigoCharacter. INMET station identifier.
nome_estacaoCharacter. Station name.
ufCharacter. Brazilian state abbreviation.
mesCharacter. Month name (Portuguese, lower-case ASCII).
decadaCharacter. Decade within month ("1", "2", "3").
valorNumeric. Climatological normal value.
var_codeCharacter. Variable identifier from normal_meta.
variable_ptCharacter. Variable label in Portuguese.
variable_enCharacter. Variable label in English.
periodCharacter. Reference period (e.g. "1991-2020").
Climate normals serve as the climatological baseline against which observed exposures are compared in epidemiological studies:
Heat-health: temperature normals reveal chronically hot municipalities for heat-wave attribution and heat-related mortality studies.
Precipitation extremes: wet-day and dry-spell normals support flood and drought exposure assessments linked to diarrhoeal disease, leptospirosis, and waterborne outbreaks.
Vector-borne diseases: humidity and temperature normals define the climatic envelope of Aedes mosquito habitat, informing dengue, chikungunya and Zika risk mapping.
Relative-risk baselines: DLNM models built with
sus_mod_dlnm() require a reference exposure; normals provide the
station-level climatological mean for that reference.
Vulnerability indices: combined with sus_mod_vulnerability_index(),
normals quantify chronic exposure as an IPCC hazard pillar component.
sus_climate_normals_meta(), sus_climate_inmet(),
sus_mod_dlnm(), sus_mod_vulnerability_index()
## Not run: # Full 1991-2020 normals (all variables) normals <- sus_climate_normals(period = "1991-2020") # Only temperature variables temp_normals <- sus_climate_normals( period = "1991-2020", target_var = c("t_max", "t_min", "t_mean_comp"), lang = "pt" ) # Browse available variables first meta <- sus_climate_normals_meta(period = "1991-2020") ## End(Not run)## Not run: # Full 1991-2020 normals (all variables) normals <- sus_climate_normals(period = "1991-2020") # Only temperature variables temp_normals <- sus_climate_normals( period = "1991-2020", target_var = c("t_max", "t_min", "t_mean_comp"), lang = "pt" ) # Browse available variables first meta <- sus_climate_normals_meta(period = "1991-2020") ## End(Not run)
Returns the normal_meta dictionary as a tibble so you can inspect
available variables and their var_code values before calling
sus_climate_normals().
sus_climate_normals_meta( period = NULL, lang = "pt", cache_dir = "~/.climasus4r_cache/normals", use_cache = TRUE, verbose = FALSE )sus_climate_normals_meta( period = NULL, lang = "pt", cache_dir = "~/.climasus4r_cache/normals", use_cache = TRUE, verbose = FALSE )
period |
Character. Filter to a specific period, or |
lang |
Character. Language for the returned label column:
|
cache_dir |
Character. Cache directory. Default:
|
use_cache |
Logical. Use cached catalogue. Default |
verbose |
Logical. Print messages. Default |
A tibble with columns var_code, variable_label, period,
var_slug, and code_link.
## Not run: sus_climate_normals_meta() sus_climate_normals_meta(period = "1991-2020", lang = "en") ## End(Not run)## Not run: sus_climate_normals_meta() sus_climate_normals_meta(period = "1991-2020", lang = "en") ## End(Not run)
sus_climate_plot_aggregate() produces exploratory visualisations for the
output of sus_climate_aggregate(). Six complementary plot types cover the
full exploratory workflow before modelling: time-series overlay, scatter with
smooth, cross-correlation (CCF), distribution, correlation matrix, and
seasonal patterns. Modelling-specific plots (DLNM surfaces, residual
diagnostics, RR tables) are deliberately excluded to avoid duplication with
the dedicated sus_mod_plot_* family.
sus_climate_plot_aggregate( df, outcome_col = NULL, climate_cols = NULL, plot_type = "timeseries", smooth_method = "loess", max_lag = 30L, alpha = 0.05, interactive = FALSE, lang = "pt", verbose = TRUE, title = NULL, source = NULL )sus_climate_plot_aggregate( df, outcome_col = NULL, climate_cols = NULL, plot_type = "timeseries", smooth_method = "loess", max_lag = 30L, alpha = 0.05, interactive = FALSE, lang = "pt", verbose = TRUE, title = NULL, source = NULL )
df |
A |
outcome_col |
Character. Name of the health-outcome column
(e.g. |
climate_cols |
Character vector of climate column names to visualise.
If |
plot_type |
Character. One of:
Default |
smooth_method |
Character. Smoothing method for the scatter plot:
|
max_lag |
Integer. Maximum lag (days) shown in the CCF plot.
Default |
alpha |
Numeric. Confidence level for CCF significance bounds
(default |
interactive |
Logical. If |
lang |
Character. Language for axis labels and titles:
|
verbose |
Logical. Print progress messages. Default |
title |
Character or |
source |
Character or |
A ggplot2 object, a patchwork object (when multiple climate
columns are supplied and patchwork is installed for "timeseries" or
"scatter" plot types), or a plotly object when interactive = TRUE.
sus_climate_aggregate(), sus_climate_plot_fill(),
sus_climate_plot_heatwaves(), sus_mod_plot_dlnm()
## Not run: # Build aggregate data (exact strategy) df_agg <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet, climate_var = "tair_dry_bulb_c", temporal_strategy = "exact" ) # Time-series overlay sus_climate_plot_aggregate(df_agg, plot_type = "timeseries", lang = "pt") # Discrete lag: correlation matrix across all lag columns df_lag <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet, climate_var = "tair_dry_bulb_c", temporal_strategy = "discrete_lag", lag_days = c(7, 14, 21) ) sus_climate_plot_aggregate(df_lag, plot_type = "corr_matrix", lang = "en") # Cross-correlation sus_climate_plot_aggregate(df_agg, plot_type = "ccf", max_lag = 21L) ## End(Not run)## Not run: # Build aggregate data (exact strategy) df_agg <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet, climate_var = "tair_dry_bulb_c", temporal_strategy = "exact" ) # Time-series overlay sus_climate_plot_aggregate(df_agg, plot_type = "timeseries", lang = "pt") # Discrete lag: correlation matrix across all lag columns df_lag <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet, climate_var = "tair_dry_bulb_c", temporal_strategy = "discrete_lag", lag_days = c(7, 14, 21) ) sus_climate_plot_aggregate(df_lag, plot_type = "corr_matrix", lang = "en") # Cross-correlation sus_climate_plot_aggregate(df_agg, plot_type = "ccf", max_lag = 21L) ## End(Not run)
Visualizes and analyzes the results from sus_climate_compute_coldwaves().
Provides multiple visualization types including a Gantt-style timeline of
events, a calendar heatmap, an intensity-vs-duration scatter plot, and an
annual trend bar chart.
sus_climate_plot_coldwaves( cw_result, type = c("timeline", "calendar", "intensity", "trend"), station_code = NULL, method = NULL, year = NULL, interactive = TRUE, color_palette = "npg", lang = "pt", save_plot = NULL )sus_climate_plot_coldwaves( cw_result, type = c("timeline", "calendar", "intensity", "trend"), station_code = NULL, method = NULL, year = NULL, interactive = TRUE, color_palette = "npg", lang = "pt", save_plot = NULL )
cw_result |
List. The output from |
type |
Character. Type of plot to generate:
|
station_code |
Character. Optional. Filter by a specific station code. |
method |
Character. Optional. Filter by a specific method (e.g.,
|
year |
Numeric. Optional. Filter by a specific year (useful for calendar plots). |
interactive |
Logical. If |
color_palette |
Character. Name of the ggsci palette to use. Default
is |
lang |
Character. Language for labels: |
save_plot |
Character. Optional file path to save the plot
(e.g., |
A ggplot or plotly object.
sus_climate_compute_coldwaves()
## Not run: cw <- df_indicators |> sus_climate_compute_coldwaves(method = c("WHO", "EHF")) sus_climate_plot_coldwaves(cw, type = "timeline", lang = "pt") sus_climate_plot_coldwaves(cw, type = "trend", interactive = FALSE) ## End(Not run)## Not run: cw <- df_indicators |> sus_climate_compute_coldwaves(method = c("WHO", "EHF")) sus_climate_plot_coldwaves(cw, type = "timeline", lang = "pt") sus_climate_plot_coldwaves(cw, type = "trend", interactive = FALSE) ## End(Not run)
Unified visualisation for gap-filling outputs of the climasus4r pipeline.
Automatically detects production mode (filled tibble) vs evaluation
mode (list with data and metrics components) and renders appropriate
interactive (plotly) or static (ggplot2) plots plus DT metric tables.
Production mode displays:
Time-series of observed (with gaps) vs imputed series.
Imputed segments as distinct markers. Consecutive imputed blocks are connected by a dotted line; isolated single points appear as dots only.
Interactive range-slider with zoom presets (plotly only).
Evaluation mode displays a 2×2 diagnostic dashboard:
Observed vs Predicted scatter with 1:1 reference line.
Residual distribution histogram.
Residuals over time (temporal-autocorrelation diagnostic).
Residuals vs observed (heteroscedasticity diagnostic).
sus_climate_plot_fill( df_filled, df_original = NULL, target_var, interactive = FALSE, output_type = c("plot", "table", "metrics", "all"), save_plot = NULL, lang = c("en", "pt", "es"), color_palette = c("npg", "aaas", "nejm", "lancet", "jama", "bmj", "jco", "frontiers", "gsea", "uchicago", "primer", "atlassian", "observable", "d3", "igv", "cosmic", "locuszoom", "ucscgb", "startrek", "tron", "futurama", "rickandmorty", "simpsons", "flatui", "bs5", "material", "tw3"), verbose = FALSE )sus_climate_plot_fill( df_filled, df_original = NULL, target_var, interactive = FALSE, output_type = c("plot", "table", "metrics", "all"), save_plot = NULL, lang = c("en", "pt", "es"), color_palette = c("npg", "aaas", "nejm", "lancet", "jama", "bmj", "jco", "frontiers", "gsea", "uchicago", "primer", "atlassian", "observable", "d3", "igv", "cosmic", "locuszoom", "ucscgb", "startrek", "tron", "futurama", "rickandmorty", "simpsons", "flatui", "bs5", "material", "tw3"), verbose = FALSE )
df_filled |
Output of |
df_original |
Raw data before gap filling, e.g. from |
target_var |
Character vector of variable(s) to visualise. |
interactive |
Logical. |
output_type |
What to return: |
save_plot |
Optional file path to save the plot (e.g. |
lang |
Language: |
color_palette |
ggsci palette name (default: |
verbose |
Print diagnostic information (default: |
Depending on output_type, returns the plot, table, metrics, or a
named list containing all four components: plot, table, metrics, data.
Visualizes and analyzes the results from sus_climate_compute_heatwaves().
It provides multiple visualization types including time series of events,
calendar heatmaps, intensity distributions, and annual summaries.
sus_climate_plot_heatwaves( hw_result, type = c("timeline", "calendar", "intensity", "trend"), station_code = NULL, method = NULL, year = NULL, interactive = TRUE, color_palette = "npg", lang = "en", save_plot = NULL )sus_climate_plot_heatwaves( hw_result, type = c("timeline", "calendar", "intensity", "trend"), station_code = NULL, method = NULL, year = NULL, interactive = TRUE, color_palette = "npg", lang = "en", save_plot = NULL )
hw_result |
List. The output from |
type |
Character. Type of plot to generate:
|
station_code |
Character. Optional. Filter by a specific station code. |
method |
Character. Optional. Filter by a specific method (e.g., "EHF", "INMET"). |
year |
Numeric. Optional. Filter by a specific year (useful for calendar plots). |
interactive |
Logical. If |
color_palette |
Character. Name of the ggsci color palette to use. Default is |
lang |
Character. Language for labels and titles: |
save_plot |
Character. Optional file path to save the plot (e.g., "plot.html" or "plot.png"). |
A ggplot or plotly object.
sus_climate_uniplu() downloads, caches, and imports data from the
Unified Brazilian Rainfall Dataset (UNIPLU-BR) — the most comprehensive
national rainfall database for Brazil, covering 21,000+ gauges from
five monitoring networks over 140 years (1885–2025).
The function implements a full processing pipeline:
Download: Single 1.6 GB ZIP from Zenodo (first call only)
Extraction: Two Parquet files cached locally for instant re-use
Standardization: Column names aligned with climasus4r conventions
Filtering: By year, state (UF), and/or monitoring network
Aggregation: Sub-daily data optionally aggregated to daily/monthly/yearly totals
sus_climate_uniplu( years = NULL, uf = NULL, network = NULL, aggregate_to = "day", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/climate", lang = "pt", verbose = TRUE )sus_climate_uniplu( years = NULL, uf = NULL, network = NULL, aggregate_to = "day", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/climate", lang = "pt", verbose = TRUE )
years |
Integer vector of year(s) to import.
Examples: |
uf |
Character vector of Brazilian state codes
(e.g., |
network |
Character vector of monitoring network(s) to include.
One or more of: |
aggregate_to |
Character. Temporal resolution for aggregating sub-daily observations into totals. One of:
When |
use_cache |
Logical. If |
cache_dir |
Character. Directory path for the disk cache.
Default: |
lang |
Character. Message language. One of:
|
verbose |
Logical. If |
A climasus_df object (subclass of tibble) at stage = "climate",
type = "uniplu". Columns:
station_codeCharacter. Unique gauge identifier (from gauge_code)
station_nameCharacter. City name of the gauge (from city)
ufCharacter. State abbreviation (from state)
latitudeNumeric. Decimal latitude, WGS84 (from lat)
longitudeNumeric. Decimal longitude, WGS84 (from long)
altitudeNumeric. Elevation in metres above sea level (from elevation)
networkCharacter. Source monitoring network
time_step_minInteger. Original temporal resolution in minutes
(e.g., 10, 60, 1440). Only present when aggregate_to = "none".
utc_offsetNumeric. Timezone offset from UTC (from utc).
Only present when aggregate_to = "none".
datePOSIXct or Date. Observation timestamp / aggregation period
rainfall_mmNumeric. Precipitation in millimetres
(sum over aggregation period, or raw value when aggregate_to = "none")
Metadata (accessible via sus_meta()):
stage"climate"
type"uniplu"
source"UNIPLU-BR"
doi"10.5281/zenodo.18883358"
yearsYears retained after filtering
ufsStates retained after filtering
networksNetworks retained after filtering
n_stationsNumber of unique gauges
n_observationsTotal rows
temporalList with start, end, unit (aggregate_to)
| Network | Operator | Period | Resolution |
| Hidroweb | ANA | 1885–2025 | Daily (1440 min) |
| INMET daily | INMET | 1889–2025 | Daily (1440 min) |
| ICEA | ICEA | 1951–2025 | Various |
| CEMADEN | CEMADEN | 2014–2025 | 10–15 min |
| Telemetria | Various | 2014–2025 | 10–60 min |
| INMET sub-daily | INMET | 2000–2025 | 60 min |
Data quality: The dataset is strictly structurally standardized. No outlier removal or physical consistency checks were applied by the data producers. Extreme or implausible values from source agencies remain. Consider applying your own quality filters for scientific analyses.
Download size: ~1.6 GB compressed. Only performed once; subsequent calls read from cached Parquet files (typically a few seconds).
Rainfall only: UNIPLU-BR contains precipitation exclusively.
For multi-variable climate data (temperature, humidity, radiation), use
sus_climate_inmet().
License: CC-BY-4.0. Cite the dataset and paper when publishing.
Dataset: Das Neves Almeida, C., Bertrand, G. F., Lemos, F. C., et al. (2026). Unified Brazilian Rainfall Dataset (UNIPLU-BR): A Standardized National Database of Point Precipitation from Major Brazilian Monitoring Networks (1885–2025). Zenodo. doi:10.5281/zenodo.18883358
Related paper: Das Neves Almeida, C., Bertrand, G. F., Lemos, F. C., et al. (2025). The design of the Brazilian Sub-Daily Rainfall dataset (BR-SDR): two decades of high-time-resolution data in Brazil. Hydrological Sciences Journal, 70(11), 1850–1862. doi:10.1080/02626667.2025.2506193
GitHub repository: https://github.com/LARHENA/UNIPLU-BR
sus_climate_inmet() for multi-variable meteorological data (INMET)
sus_climate_aggregate() for health-climate temporal integration
sus_climate_fill_inmet() for ML-based gap filling
## Not run: # Daily rainfall for Rio Grande do Norte, last 2 years (default) rain_rn <- sus_climate_uniplu(uf = "RN") # Multiple states, specific years, daily totals rain_ne <- sus_climate_uniplu( years = 2015:2024, uf = c("RN", "CE", "PB", "PE"), aggregate_to = "day" ) # Only ANA/Hidroweb network, monthly totals rain_hidroweb <- sus_climate_uniplu( years = 2000:2020, network = "Hidroweb", aggregate_to = "month" ) # Raw sub-daily data (no aggregation) rain_raw <- sus_climate_uniplu( years = 2023, uf = "SP", network = "CEMADEN", aggregate_to = "none" ) # Check metadata sus_meta(rain_rn) # Inspect stations dplyr::distinct(rain_rn, station_code, station_name, latitude, longitude) # Integrate with health data (requires prior sus_spatial_join()) health_climate <- sus_climate_aggregate( health_data = health_spatial, climate_data = rain_rn, climate_var = "rainfall_mm", temporal_strategy = "moving_window", window_days = 14 ) ## End(Not run)## Not run: # Daily rainfall for Rio Grande do Norte, last 2 years (default) rain_rn <- sus_climate_uniplu(uf = "RN") # Multiple states, specific years, daily totals rain_ne <- sus_climate_uniplu( years = 2015:2024, uf = c("RN", "CE", "PB", "PE"), aggregate_to = "day" ) # Only ANA/Hidroweb network, monthly totals rain_hidroweb <- sus_climate_uniplu( years = 2000:2020, network = "Hidroweb", aggregate_to = "month" ) # Raw sub-daily data (no aggregation) rain_raw <- sus_climate_uniplu( years = 2023, uf = "SP", network = "CEMADEN", aggregate_to = "none" ) # Check metadata sus_meta(rain_rn) # Inspect stations dplyr::distinct(rain_rn, station_code, station_name, latitude, longitude) # Integrate with health data (requires prior sus_spatial_join()) health_climate <- sus_climate_aggregate( health_data = health_spatial, climate_data = rain_rn, climate_var = "rainfall_mm", temporal_strategy = "moving_window", window_days = 14 ) ## End(Not run)
Aggregates individual-level health data into time series counts by specified time units and grouping variables. This function is essential for preparing data for time series analysis, DLNM models, and other temporal epidemiological methods.
sus_data_aggregate( df, time_unit = "day", fun = "count", group_by = NULL, value_col = NULL, complete_dates = FALSE, date_col = NULL, backend = "arrow", lang = "pt", verbose = TRUE )sus_data_aggregate( df, time_unit = "day", fun = "count", group_by = NULL, value_col = NULL, complete_dates = FALSE, date_col = NULL, backend = "arrow", lang = "pt", verbose = TRUE )
df |
A data frame containing health data (output from |
time_unit |
Character string specifying the temporal aggregation unit.
Standard units: |
fun |
Character string or list of functions specifying the aggregation function(s).
Options: |
group_by |
Character vector with names of columns to group by (e.g.,
|
value_col |
Character string with the name of the column to aggregate when
using functions other than |
complete_dates |
Logical. If |
date_col |
Character string with the name of the date column to use for
aggregation. If |
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
lang |
Character string specifying the language for messages. Options:
|
verbose |
Logical. If |
New Features:
Multiple aggregation functions: Beyond counting, you can now calculate mean, sum, median, percentiles, etc., useful for climate and environmental data.
Smart column naming: The aggregated column is automatically named
based on the health system (e.g., n_deaths for SIM, n_hospitalizations
for SIH-RD, n_births for SINASC, n_cases for SINAN, n_procedures for SIA, and n_establishments, for CNES).
Epidemiological Use Cases:
Daily/Weekly: Standard time series analysis, DLNM for short-term effects
Pentads (5 days): Heat wave analysis, smoothing daily noise
Fortnightly (14 days): Diseases with longer incubation periods
Monthly: Seasonal patterns, long-term trends
Quarterly: SUS management reports, policy evaluation
Seasonal: Dengue, Influenza, respiratory diseases aligned with Brazilian climate
Yearly: Long-term trend analysis, climate change impacts
Brazilian Seasons (when time_unit = "season"):
Summer (Verao): December-January-February (DJF)
Autumn (Outono): March-April-May (MAM)
Winter (Inverno): June-July-August (JJA)
Spring (Primavera): September-October-November (SON)
A tibble with aggregated data containing:
date: The aggregated date (start of period)
Grouping columns (if group_by was specified)
Aggregated value column(s) with smart names based on system and function
## Not run: library(climasus4r) # Basic daily aggregation df_daily <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize() %>% sus_data_filter_cid(disease_group = "respiratory") %>% sus_data_aggregate(time_unit = "day") # Pentad aggregation (5-day periods) for heat wave analysis df_pentad <- sus_data_aggregate(df, time_unit = "5 days") # Fortnightly aggregation for diseases with longer incubation df_fortnightly <- sus_data_aggregate(df, time_unit = "14 days") # Monthly aggregation by municipality df_monthly <- sus_data_aggregate( df, time_unit = "month", group_by = c("race", "sex"), lang = "pt" ) # Quarterly aggregation for SUS reports df_quarterly <- sus_data_aggregate(df, time_unit = "quarter") # Seasonal aggregation for dengue analysis (Brazilian seasons) df_seasonal <- sus_data_aggregate( df, time_unit = "season" ) # Weekly aggregation by age group and sex df_weekly <- sus_data_aggregate( df, time_unit = "week", group_by = c("age_group", "sex") #age_group comes from `sus_data_create_variables()` ) ## End(Not run)## Not run: library(climasus4r) # Basic daily aggregation df_daily <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize() %>% sus_data_filter_cid(disease_group = "respiratory") %>% sus_data_aggregate(time_unit = "day") # Pentad aggregation (5-day periods) for heat wave analysis df_pentad <- sus_data_aggregate(df, time_unit = "5 days") # Fortnightly aggregation for diseases with longer incubation df_fortnightly <- sus_data_aggregate(df, time_unit = "14 days") # Monthly aggregation by municipality df_monthly <- sus_data_aggregate( df, time_unit = "month", group_by = c("race", "sex"), lang = "pt" ) # Quarterly aggregation for SUS reports df_quarterly <- sus_data_aggregate(df, time_unit = "quarter") # Seasonal aggregation for dengue analysis (Brazilian seasons) df_seasonal <- sus_data_aggregate( df, time_unit = "season" ) # Weekly aggregation by age group and sex df_weekly <- sus_data_aggregate( df, time_unit = "week", group_by = c("age_group", "sex") #age_group comes from `sus_data_create_variables()` ) ## End(Not run)
Opens an interactive HTML interface to explore disease groups and climate factors
for use with sus_data_filter_cid().
sus_data_cid_select( lang = "pt", output = "browser", filter_climate = FALSE, verbose = TRUE )sus_data_cid_select( lang = "pt", output = "browser", filter_climate = FALSE, verbose = TRUE )
lang |
Character string specifying language. Options: |
output |
Character string specifying output format. Options:
|
filter_climate |
Logical. If |
verbose |
Logical. If |
This function helps users discover available disease groups without needing to know specific ICD-10 codes. The interactive interface allows:
Multi-select disease groups (Ctrl/Cmd + Click)
Filter by climate factors (temperature, precipitation, etc.)
Copy group names for use in sus_data_filter_cid()
View ICD-10 codes and descriptions
Depending on output:
"browser": Opens HTML interface, returns invisible data.frame
"console": Prints summary, returns invisible data.frame
## Not run: # Open interactive explorer sus_data_cid_select() # Explore only climate-sensitive diseases sus_data_cid_select(filter_climate = TRUE) # Get disease group names for programmatic use groups <- sus_data_cid_select( lang = "pt" ) # Use in sus_data_filter_cid data <- sus_data_filter_cid( df = my_data, disease_group = groups[1] ) ## End(Not run)## Not run: # Open interactive explorer sus_data_cid_select() # Explore only climate-sensitive diseases sus_data_cid_select(filter_climate = TRUE) # Get disease group names for programmatic use groups <- sus_data_cid_select( lang = "pt" ) # Use in sus_data_filter_cid data <- sus_data_filter_cid( df = my_data, disease_group = groups[1] ) ## End(Not run)
This function scans text columns in a data.frame and corrects common encoding
problems (e.g., "Sao Paulo") that occur when Latin1 data is
incorrectly read as UTF-8. It acts as a final auditor to ensure all text data
is properly encoded, complementing the preprocessing done by microdatasus.
Supports multilingual output messages (English, Portuguese, Spanish).
sus_data_clean_encoding(df, backend = "arrow", lang = "pt", verbose = TRUE)sus_data_clean_encoding(df, backend = "arrow", lang = "pt", verbose = TRUE)
df |
A |
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
lang |
Character. Language for UI messages. Options: "en" (English), "pt" (Portuguese, default), "es" (Spanish). |
verbose |
Logical. If TRUE, prints a report of columns checked and corrected. Default is TRUE. |
A data.frame with corrected text columns.
## Not run: # Create a sample dataset with encoding issues # In real data, this might happen with Brazilian Portuguese text df_problem <- data.frame( id = 1:3, city = c("Sao Paulo", "Rio de Janeiro", "Belo Horizonte"), state = c("SP", "RJ", "MG"), stringsAsFactors = FALSE ) # Simulate encoding issue (for demonstration only) # In practice, this happens when Latin1 text is read as UTF-8 # Correct encoding with English messages df_clean_en <- sus_data_clean_encoding(df_problem, lang = "en") # Correct encoding with Portuguese messages df_clean_pt <- sus_data_clean_encoding(df_problem, lang = "pt") # Correct encoding with Spanish messages df_clean_es <- sus_data_clean_encoding(df_problem, lang = "es") # Use in a pipeline df_clean <- sus_data_import(uf = "RJ", year = 2022, system = "SIM") %>% sus_data_clean_encoding(lang = "pt") ## End(Not run)## Not run: # Create a sample dataset with encoding issues # In real data, this might happen with Brazilian Portuguese text df_problem <- data.frame( id = 1:3, city = c("Sao Paulo", "Rio de Janeiro", "Belo Horizonte"), state = c("SP", "RJ", "MG"), stringsAsFactors = FALSE ) # Simulate encoding issue (for demonstration only) # In practice, this happens when Latin1 text is read as UTF-8 # Correct encoding with English messages df_clean_en <- sus_data_clean_encoding(df_problem, lang = "en") # Correct encoding with Portuguese messages df_clean_pt <- sus_data_clean_encoding(df_problem, lang = "pt") # Correct encoding with Spanish messages df_clean_es <- sus_data_clean_encoding(df_problem, lang = "es") # Use in a pipeline df_clean <- sus_data_import(uf = "RJ", year = 2022, system = "SIM") %>% sus_data_clean_encoding(lang = "pt") ## End(Not run)
Creates commonly used derived variables from health data across ALL SUS systems (SIM, SINAN, SIH, SIA, SINASC, CNES), including age groups, calendar variables, and other epidemiologically relevant categorizations. Features age calculation that handles different data formats across systems.
sus_data_create_variables( df, create_age_groups = TRUE, age_breaks = c(0, 5, 15, 60, Inf), age_labels = NULL, create_calendar_vars = TRUE, create_climate_vars = TRUE, climate_region = NULL, date_col = NULL, age_col = NULL, hemisphere = "south", backend = "arrow", lang = "pt", verbose = TRUE )sus_data_create_variables( df, create_age_groups = TRUE, age_breaks = c(0, 5, 15, 60, Inf), age_labels = NULL, create_calendar_vars = TRUE, create_climate_vars = TRUE, climate_region = NULL, date_col = NULL, age_col = NULL, hemisphere = "south", backend = "arrow", lang = "pt", verbose = TRUE )
df |
A data frame containing health data from any SUS system. |
create_age_groups |
Logical. If
If age is successfully determined, the following variables may be created:
All age group variables are created only if age can be reliably determined. If age cannot be inferred, the function will stop with an informative error. |
age_breaks |
Numeric vector specifying the breakpoints for age groups.
Default is |
age_labels |
Character vector with labels for age groups. If |
create_calendar_vars |
Logical. If |
create_climate_vars |
Logical. Se |
climate_region |
Character. Regiao climatica para calculos sazonais. Opcoes: "norte", "nordeste", "centro-oeste", "sudeste", "sul". |
date_col |
Character string with the name of the date column. If |
age_col |
Character string with the name of the age column (in years).
If
|
hemisphere |
Character string specifying the hemisphere for season
calculation. Options: |
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
lang |
Character string specifying the language for variable labels and
messages. Options: |
verbose |
Logical. If |
Age Calculation (Hierarchical Logic):
The function uses a 3-tier hierarchy to ensure age is calculated correctly across all SUS systems:
Direct Age Column (Fastest): If a column with age in years already exists (common in SIM after microdatasus processing), uses it directly.
Date Calculation (Gold Standard): If birth date and event date are available,
calculates exact age as: interval(birth_date, event_date) / years(1).
This is the most accurate method and works for:
SINAN: Has DTNASC and DT_NOTIFIC
SIH: Has NASC and DT_INTER
SINASC: Has DTNASC (mother) and DTNASC (newborn)
DATASUS Code Decoder (Fallback): If dates are missing (common in anonymized data), decodes the composite age code used by DATASUS:
Codes starting with 1: Hours (converted to 0 years)
Codes starting with 2: Days (converted to 0 years)
Codes starting with 3: Months (converted to 0 years for <12 months)
Codes starting with 4: Years (e.g., 4035 = 35 years)
Codes starting with 5: 100+ years (e.g., 5105 = 105 years)
Age Groups: Creates a factor variable age_group based on the specified
breaks and labels. Common epidemiological categories:
Pediatric: 0-4, 5-14, 15-19
Adult: 20-39, 40-59, 60+
Elderly: 65-74, 75-84, 85+
Climate-Health: 0-4, 5-64, 65+ (vulnerable populations)
Calendar Variables (when create_calendar_vars = TRUE):
day_of_week: Day of the week (1 = Monday, 7 = Sunday)
day_of_week_name: Day name (e.g., "Monday", "Segunda-feira")
month: Month number (1-12)
month_name: Month name (e.g., "January", "Janeiro")
year: Year
quarter: Quarter (1-4)
season: Season (Summer, Autumn, Winter, Spring)
is_weekend: Logical indicating if date is weekend
day_of_year: Day of year (1-365/366)
semester: Semester (1 or 2)
Seasons are calculated based on hemisphere:
Southern Hemisphere (Brazil): Summer (Dec-Feb), Autumn (Mar-May), Winter (Jun-Aug), Spring (Sep-Nov)
Northern Hemisphere: Summer (Jun-Aug), Autumn (Sep-Nov), Winter (Dec-Feb), Spring (Mar-May)
The input data frame with additional columns for the created variables.
## Not run: library(climasus4r) # ===== EXAMPLE 1: SIM (Mortality) - Age already calculated ===== df_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") |> sus_data_standardize(lang = "en") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 5, 65, Inf), age_labels = c("0-4", "5-64", "65+"), create_calendar_vars = TRUE, lang = "en" ) # Uses direct age column (fastest) # ===== EXAMPLE 2: SINAN (Dengue) - Calculate from dates ===== df_sinan <- sus_data_import(uf = "RJ", year = 2023, system = "SINAN-DENGUE") |> sus_data_standardize(lang = "pt") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 15, 60, Inf), create_calendar_vars = TRUE, lang = "pt" ) # Calculates age from DTNASC and DT_NOTIFIC (gold standard) # ===== EXAMPLE 3: SIH (Hospitalizations) - Decode age codes ===== df_sih <- sus_data_import(uf = "MG", year = 2023, system = "SIH-RD") |> sus_data_standardize(lang = "es") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 18, 60, Inf), age_labels = c("0-17", "18-59", "60+"), create_calendar_vars = TRUE, lang = "es" ) # Decodes DATASUS age codes if dates are missing (fallback) # ===== EXAMPLE 4: Custom age groups for elderly analysis ===== df_elderly <- sus_data_create_variables( df, create_age_groups = TRUE, age_breaks = c(60, 70, 80, 90, Inf), age_labels = c("60-69", "70-79", "80-89", "90+"), lang = "pt" ) # ===== EXAMPLE 5: Calendar variables and climate variables ===== df_calendar_climate <- sus_data_create_variables( df, create_calendar_vars = TRUE, create_semester = TRUE, create_climate_vars = TRUE, climate_region = "Norte" ) ## End(Not run)## Not run: library(climasus4r) # ===== EXAMPLE 1: SIM (Mortality) - Age already calculated ===== df_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") |> sus_data_standardize(lang = "en") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 5, 65, Inf), age_labels = c("0-4", "5-64", "65+"), create_calendar_vars = TRUE, lang = "en" ) # Uses direct age column (fastest) # ===== EXAMPLE 2: SINAN (Dengue) - Calculate from dates ===== df_sinan <- sus_data_import(uf = "RJ", year = 2023, system = "SINAN-DENGUE") |> sus_data_standardize(lang = "pt") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 15, 60, Inf), create_calendar_vars = TRUE, lang = "pt" ) # Calculates age from DTNASC and DT_NOTIFIC (gold standard) # ===== EXAMPLE 3: SIH (Hospitalizations) - Decode age codes ===== df_sih <- sus_data_import(uf = "MG", year = 2023, system = "SIH-RD") |> sus_data_standardize(lang = "es") |> sus_data_create_variables( create_age_groups = TRUE, age_breaks = c(0, 18, 60, Inf), age_labels = c("0-17", "18-59", "60+"), create_calendar_vars = TRUE, lang = "es" ) # Decodes DATASUS age codes if dates are missing (fallback) # ===== EXAMPLE 4: Custom age groups for elderly analysis ===== df_elderly <- sus_data_create_variables( df, create_age_groups = TRUE, age_breaks = c(60, 70, 80, 90, Inf), age_labels = c("60-69", "70-79", "80-89", "90+"), lang = "pt" ) # ===== EXAMPLE 5: Calendar variables and climate variables ===== df_calendar_climate <- sus_data_create_variables( df, create_calendar_vars = TRUE, create_semester = TRUE, create_climate_vars = TRUE, climate_region = "Norte" ) ## End(Not run)
Exports processed health data to a file with optional metadata documentation to ensure reproducibility. Supports multiple file formats optimized for different use cases, including GeoArrow/GeoParquet for spatial data.
sus_data_export( df, file_path, format = NULL, include_metadata = TRUE, metadata = NULL, compress = TRUE, compression_level = 6, overwrite = FALSE, lang = "pt", verbose = TRUE )sus_data_export( df, file_path, format = NULL, include_metadata = TRUE, metadata = NULL, compress = TRUE, compression_level = 6, overwrite = FALSE, lang = "pt", verbose = TRUE )
df |
A data frame or sf object containing the processed health data to export. |
file_path |
Character string specifying the output file path. The file
extension determines the format if |
format |
Character string specifying the output format. Options:
|
include_metadata |
Logical. If |
metadata |
Named list containing custom metadata to save. Common fields:
If |
compress |
Logical. If |
compression_level |
Integer specifying compression level (1-9). Higher values = smaller files but slower. Default is 6. Only applies to formats that support compression. |
overwrite |
Logical. If |
lang |
Character string specifying the language for messages. Options:
|
verbose |
Logical. If |
File Formats:
RDS (.rds): Native R format. Fast, compressed, preserves all
R object attributes. Best for R-only workflows.
Parquet (.parquet): Columnar format. Excellent
compression, fast reading, language-agnostic. Best for large datasets
and interoperability with Python, Spark, etc.
GeoParquet (.geoparquet, .parquet for sf objects): Optimized
columnar format for spatial data. Combines benefits of Parquet with
efficient geometry storage. 50-90% smaller than shapefiles, 10-100x faster.
Shapefile (.shp or .gpkg): Traditional GIS format. Widely supported but
inefficient for large datasets. Multiple files generated (.shp, .shx, .dbf, etc.).
CSV (.csv): Universal text format. Human-readable, compatible
with all software. Best for sharing with non-R users. Larger file size.
Note: Geometries are exported as WKT (Well-Known Text) for spatial data.
Automatic Format Detection:
If format = NULL, the function automatically detects the best format:
If input is an sf object and extension is .parquet → "geoparquet"
If input is an sf object and extension is .shp → "shapefile"
Otherwise, infers from file extension
Spatial Data Export:
When exporting sf objects (spatial data from sus_spatial_join()):
Recommended: Use GeoParquet format for optimal performance
GeoParquet preserves CRS, geometry types, and all attributes
Compatible with QGIS, Python (geopandas), and other GIS software
Significantly faster and smaller than shapefiles
Invisibly returns the file path of the exported data. If metadata was saved, also returns the metadata file path as an attribute.
## Not run: library(climasus4r) # Export regular data frame to RDS sus_data_export(df_final, "output/data.rds") # Export spatial data to GeoParquet (RECOMMENDED) sf_result <- sus_spatial_join(df, level = "munic") sus_data_export( sf_result, file_path = "output/spatial_data.geoparquet", format = "geoparquet" # Auto-detected if extension is .parquet ) # Export spatial data to Shapefile (traditional) sus_data_export( sf_result, file_path = "output/spatial_data.shp", format = "shapefile" ) # Export to Arrow with custom metadata sus_data_export( df_final, file_path = "output/respiratory_sp_2023.parquet", format = "parquet", metadata = list( source_system = "SIM-DO", states = "SP", years = 2023, disease_groups = "respiratory", author = "Max Anjos" ) ) ## End(Not run)## Not run: library(climasus4r) # Export regular data frame to RDS sus_data_export(df_final, "output/data.rds") # Export spatial data to GeoParquet (RECOMMENDED) sf_result <- sus_spatial_join(df, level = "munic") sus_data_export( sf_result, file_path = "output/spatial_data.geoparquet", format = "geoparquet" # Auto-detected if extension is .parquet ) # Export spatial data to Shapefile (traditional) sus_data_export( sf_result, file_path = "output/spatial_data.shp", format = "shapefile" ) # Export to Arrow with custom metadata sus_data_export( df_final, file_path = "output/respiratory_sp_2023.parquet", format = "parquet", metadata = list( source_system = "SIM-DO", states = "SP", years = 2023, disease_groups = "respiratory", author = "Max Anjos" ) ) ## End(Not run)
Filters Brazilian Unified Health System (SUS) data based on ICD-10 codes. (International Classification of Diseases, 10th Revision) or predefined epidemiological disease groups. This function supports complex filtering scenarios including specific codes, code ranges, chapters, and 50+ disease groups relevant to epidemiological research in Brazil. Includes specialized support for SUS-specific coding practices and multilingual interface (English, Portuguese, Spanish).
sus_data_filter_cid( df, icd_codes = NULL, disease_group = NULL, icd_column = NULL, match_type = "starts_with", backend = "arrow", lang = "pt", verbose = TRUE )sus_data_filter_cid( df, icd_codes = NULL, disease_group = NULL, icd_column = NULL, match_type = "starts_with", backend = "arrow", lang = "pt", verbose = TRUE )
df |
A |
icd_codes |
A character vector of ICD-10 codes, ranges, or categories. Multiple syntaxes are supported: Basic filtering:
Range filtering:
Chapter filtering:
Special SUS categories:
Brazilian epidemiological priorities:
Note: Either |
disease_group |
Character. Name of predefined disease group (e.g., "dengue",
"cardiovascular", "respiratory"). Use |
icd_column |
Character. Name of the column containing ICD-10 codes. If NULL (default), the function attempts auto-detection from common SUS column names in this priority order:
|
match_type |
Character. Type of matching algorithm:
|
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
lang |
Character. Language for user interface messages, warnings, and documentation. Options:
|
verbose |
Logical. If TRUE (default), prints detailed filtering information including: records processed, match statistics, common coding issues detected, and time elapsed. |
The function automatically identifies the appropriate ICD column based on the health system
The function includes 50+ predefined epidemiological groups organized by:
ICD Chapters: All major disease categories (A00-Y98)
Climate-Sensitive Diseases: Vector-borne, waterborne, heat-related, etc.
Specific Conditions: Dengue, malaria, cardiovascular, respiratory, etc.
Syndromic Groups: Fever, respiratory, diarrheal syndromes
Age-Specific Groups: Pediatric, elderly populations
Each group includes:
ICD code ranges
Multilingual labels and descriptions
Climate sensitivity flag
Associated climate factors
Use list_disease_groups() to see all available groups and their details.
A filtered data.frame or tibble containing only records matching
the specified ICD-10 codes or disease group. The output preserves all original columns
World Health Organization. (2016). ICD-10 International Statistical Classification of Diseases and Related Health Problems. 10th Revision.
Brazilian Ministry of Health. (2023). Classificacao Estatistica Internacional de Doencas e Problemas Relacionados a Saude - CID-10. DATASUS. http://datasus.saude.gov.br/cid10
## Not run: # Example 1: Filter by explicit ICD codes df_cardio <- sus_data_filter_cid( sim_data, icd_codes = "I00-I99", lang = "en" ) # Example 2: Filter by disease group (easier!) df_dengue <- sus_data_filter_cid( sinan_data, disease_group = "dengue", lang = "pt" ) # Example 3: Climate-sensitive diseases df_climate <- sus_data_filter_cid( sim_data, disease_group = "climate_sensitive_all", lang = "en" ) # Example 4: Multiple specific codes df_ami_stroke <- sus_data_filter_cid( sih_data, icd_codes = c("I21", "I22", "I63", "I64"), lang = "es" ) # Example 5: Respiratory diseases in children df_pediatric <- sus_data_filter_cid( sih_data, disease_group = "pediatric_respiratory", lang = "pt" ) # List all available disease groups list_disease_groups(lang = "pt") # List only climate-sensitive groups list_disease_groups(climate_sensitive_only = TRUE, lang = "en") # Get details about a specific group get_disease_group_details("dengue", lang = "pt") ## End(Not run)## Not run: # Example 1: Filter by explicit ICD codes df_cardio <- sus_data_filter_cid( sim_data, icd_codes = "I00-I99", lang = "en" ) # Example 2: Filter by disease group (easier!) df_dengue <- sus_data_filter_cid( sinan_data, disease_group = "dengue", lang = "pt" ) # Example 3: Climate-sensitive diseases df_climate <- sus_data_filter_cid( sim_data, disease_group = "climate_sensitive_all", lang = "en" ) # Example 4: Multiple specific codes df_ami_stroke <- sus_data_filter_cid( sih_data, icd_codes = c("I21", "I22", "I63", "I64"), lang = "es" ) # Example 5: Respiratory diseases in children df_pediatric <- sus_data_filter_cid( sih_data, disease_group = "pediatric_respiratory", lang = "pt" ) # List all available disease groups list_disease_groups(lang = "pt") # List only climate-sensitive groups list_disease_groups(climate_sensitive_only = TRUE, lang = "en") # Get details about a specific group get_disease_group_details("dengue", lang = "pt") ## End(Not run)
Filters health data based on demographic characteristics such as sex, race,
age range, education level, region, and municipality. This function complements
sus_data_filter_cid() by enabling stratified analyses by population subgroups.
sus_data_filter_demographics( df, sex = NULL, race = NULL, age_range = NULL, education = NULL, region = NULL, city = NULL, municipality_code = NULL, drop_ignored = FALSE, backend = "arrow", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )sus_data_filter_demographics( df, sex = NULL, race = NULL, age_range = NULL, education = NULL, region = NULL, city = NULL, municipality_code = NULL, drop_ignored = FALSE, backend = "arrow", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )
df |
A |
sex |
Character vector specifying sex categories to include. Accepts
values in English, Portuguese, or Spanish (e.g., |
race |
Character vector specifying race/color categories to include.
Accepts IBGE standard categories in multiple languages. If |
age_range |
Numeric vector of length 2 specifying the age range
|
education |
Character vector specifying education levels to include.
If |
region |
A string indicating a predefined group of states or regions (supports multilingual names PT, EN, ES). See Details. |
city |
Character vector of municipality names (e.g., |
municipality_code |
Character or numeric vector specifying municipality
codes (IBGE 6 or 7-digit codes) to include. If |
drop_ignored |
Logical. If |
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
use_cache |
Logical. If |
cache_dir |
Character string specifying the directory to store cached
files. Default is |
lang |
Character string specifying the language for messages.
Options: |
verbose |
Logical. If |
The function automatically detects column names in different languages and
standardisations. It handles both original DATASUS column names and
standardised names from sus_data_standardize().
Sex categories (case-insensitive):
English: "Male", "Female"
Portuguese: "Masculino", "Feminino"
Spanish: "Masculino", "Femenino"
Race/Color categories (IBGE standard):
English: "White", "Black", "Yellow", "Brown", "Indigenous"
Portuguese: "Branca", "Preta", "Amarela", "Parda", "Indigena"
Spanish: "Blanca", "Negra", "Amarilla", "Parda", "Indigena"
IBGE Macro-regions:
"norte": c("AC", "AP", "AM", "PA", "RO", "RR", "TO")
"nordeste": c("AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE")
"centro_oeste": c("DF", "GO", "MT", "MS")
"sudeste": c("ES", "MG", "RJ", "SP")
"sul": c("PR", "RS", "SC")
Biomes (Ecological Borders):
"amazonia_legal": c("AC", "AP", "AM", "PA", "RO", "RR", "MT", "MA", "TO")
"mata_atlantica": c("AL", "BA", "CE", "ES", "GO", "MA", "MG", "MS", "PB", "PE", "PI", "PR", "RJ", "RN", "RS", "SC", "SE", "SP")
"caatinga": c("AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE", "MG")
"cerrado": c("BA", "DF", "GO", "MA", "MG", "MS", "MT", "PA", "PI", "PR", "RO", "SP", "TO")
"pantanal": c("MT", "MS")
"pampa": c("RS")
Hydrography & Climate:
"bacia_amazonia": c("AC", "AM", "AP", "MT", "PA", "RO", "RR")
"bacia_sao_francisco": c("AL", "BA", "DF", "GO", "MG", "PE", "SE")
"bacia_parana": c("GO", "MG", "MS", "PR", "SP")
"bacia_tocantins": c("GO", "MA", "PA", "TO")
"semi_arido": c("AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE", "MG")
Health, Agriculture & Geopolitics:
"matopiba": c("MA", "TO", "PI", "BA")
"arco_desmatamento": c("RO", "AC", "AM", "PA", "MT", "MA")
"dengue_hyperendemic": c("GO", "MS", "MT", "PR", "RJ", "SP")
"sudene": c("AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE", "MG", "ES")
"fronteira_brasil": c("AC", "AM", "AP", "MT", "MS", "PA", "PR", "RO", "RR", "RS", "SC")
A climasus_df filtered by all specified demographic criteria.
## Not run: library(climasus4r) # Filter by sex only df_women <- sus_data_filter_demographics(df, sex = "Female") # Filter by age range (elderly, 65+) df_elderly <- sus_data_filter_demographics(df, age_range = c(65, Inf)) # Filter by city name (with accent tolerance) df_natal <- sus_data_filter_demographics(df, city = "Natal", lang = "pt") # Filter by multiple city names df_capitals <- sus_data_filter_demographics( df, city = c("Sao Paulo", "Rio de Janeiro", "Fortaleza"), #Usar acentos se preferir lang = "pt" ) # Mix: city names + explicit codes (union) df_subset <- sus_data_filter_demographics( df, city = "Natal", municipality_code = "3550308", lang = "pt" ) # Complex filtering df_children <- sus_data_filter_demographics( df, age_range = c(0, 5), region = "Norte", lang = "pt" ) ## End(Not run)## Not run: library(climasus4r) # Filter by sex only df_women <- sus_data_filter_demographics(df, sex = "Female") # Filter by age range (elderly, 65+) df_elderly <- sus_data_filter_demographics(df, age_range = c(65, Inf)) # Filter by city name (with accent tolerance) df_natal <- sus_data_filter_demographics(df, city = "Natal", lang = "pt") # Filter by multiple city names df_capitals <- sus_data_filter_demographics( df, city = c("Sao Paulo", "Rio de Janeiro", "Fortaleza"), #Usar acentos se preferir lang = "pt" ) # Mix: city names + explicit codes (union) df_subset <- sus_data_filter_demographics( df, city = "Natal", municipality_code = "3550308", lang = "pt" ) # Complex filtering df_children <- sus_data_filter_demographics( df, age_range = c(0, 5), region = "Norte", lang = "pt" ) ## End(Not run)
This function acts as a wrapper for microdatasus::fetch_datasus,
simplifying the download and reading of data from Brazilian public health
information systems (SIM, SINAN, SIH, SIA, CNES, SINASC).
It includes parallel processing, caching, and user-friendly CLI feedback.
sus_data_import( uf = NULL, region = NULL, year, month = NULL, system, backend = "arrow", city = NULL, municipality_code = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/data", force_redownload = FALSE, parallel = FALSE, workers = 4, lang = "pt", verbose = TRUE )sus_data_import( uf = NULL, region = NULL, year, month = NULL, system, backend = "arrow", city = NULL, municipality_code = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/data", force_redownload = FALSE, parallel = FALSE, workers = 4, lang = "pt", verbose = TRUE )
uf |
A string or vector of strings with state abbreviations (igonered if 'region' is provided) (e.g., "AM", c("SP", "RJ")). Valid UF codes: AC, AL, AP, AM, BA, CE, DF, ES, GO, MA, MT, MS, MG, PA, PB, PR, PE, PI, RJ, RN, RS, RO, RR, SC, SP, SE, TO. |
region |
A string indicating a predefined group of states (supports multilingual names PT, EN, ES). Available regions: IBGE Macro-regions:
Biomes (Ecological Borders):
Hydrography & Climate:
Health, Agriculture & Geopolitics:
|
year |
An integer or vector of integers with the desired years (4 digits). |
month |
An integer or vector of integers with the desired months (1-12). This argument is only used with monthly-based health information systems: SIH, CNES, and SIA. For annual systems (SIM, SINAN, SINASC), this parameter is ignored. |
system |
A string indicating the information system. Available systems: Mortality Systems (SIM - Mortality Information System):
Hospitalization Systems (SIH - Hospital Information System):
Notifiable Diseases (SINAN - Notifiable Diseases Information System):
Outpatient Systems (SIA - Outpatient Information System):
Health Establishments (CNES - National Health Establishment Registry):
Live Births (SINASC - Live Birth Information System):
|
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
city |
Character vector of municipality names (e.g., |
municipality_code |
Character or numeric vector of 6 or 7-digit IBGE
municipality codes. Applied independently from |
use_cache |
Logical. If TRUE (default), will use cached data to avoid re-downloads. Cache is based on UF, year, month, and system parameters. |
cache_dir |
Character. Directory to store cached files. Default is "~/.climasus4r_cache/data". |
force_redownload |
Logical. If TRUE, ignores cache and re-downloads everything. Useful when you suspect cached data is corrupted or outdated. |
parallel |
Logical. If TRUE (default), will use parallel processing for multiple UF/year combinations. Significantly speeds up bulk downloads. |
workers |
Integer. Number of parallel workers to use. Default is 4. Set to 1 to disable parallel processing. |
lang |
Character string specifying the language for variable labels and
messages. Options: |
verbose |
Logical. If TRUE (default), prints detailed progress information including cache status, download progress, and time estimates. |
All data is sourced from the Brazilian Ministry of Health's DATASUS portal (http://datasus.saude.gov.br).
The cache uses SHA-256 hashing of parameters to create unique cache keys. Cached files are stored as compressed RDS files and include metadata about the download date and parameter combination. Cache is automatically invalidated after 30 days for dynamic systems (CNES, SIA, SIH) and 365 days for static systems (SIM, SINAN, SINASC).
When downloading data for multiple states or years, parallel processing
can reduce download time by up to 70%. The function uses future.apply
internally. For large downloads (>100 files), consider increasing workers
up to 8 (if your system has sufficient cores and memory).
A tibble (or data.frame) with the requested data, combining
multiple UFs/years when requested. The output includes:
All original variables from the DATASUS system
Additional metadata columns: source_system, download_timestamp
Standardized date formats (Date objects instead of strings)
UTF-8 encoded character variables
Note: Large datasets (especially SIA and SIH) may require significant memory (1GB+ for national annual data).
Brazilian Ministry of Health. DATASUS. http://datasus.saude.gov.br
SALDANHA, Raphael de Freitas; BASTOS, Ronaldo Rocha; BARCELLOS, Christovam. Microdatasus: pacote para download e pre-processamento de microdados do Departamento de Informatica do SUS (DATASUS). Cad. Saude Publica, Rio de Janeiro , v. 35, n. 9, e00032419, 2019. Available from https://doi.org/10.1590/0102-311x00032419.
Official DATASUS documentation: http://datasus.saude.gov.br
Microdatasus package: https://github.com/rfsaldanha/microdatasus
## Not run: # Basic example: Mortality data for Rio de Janeiro in 2022 df_sim <- sus_data_import( uf = "RJ", year = 2022, system = "SIM-DO", use_cache = TRUE ) # Dengue cases for two states with parallel processing df_dengue <- sus_data_import( uf = c("SP", "MG"), year = 2023, system = "SINAN-DENGUE", parallel = TRUE, workers = 3 ) # Hospitalizations with monthly specification df_hospital <- sus_data_import( uf = "SP", year = 2024, month = 1:6, # January to June system = "SIH-RD", verbose = TRUE ) # Force re-download ignoring cache df_births <- sus_data_import( uf = "BA", year = 2020:2022, system = "SINASC", use_cache = TRUE, force_redownload = TRUE # Refresh cached data ) ## End(Not run)## Not run: # Basic example: Mortality data for Rio de Janeiro in 2022 df_sim <- sus_data_import( uf = "RJ", year = 2022, system = "SIM-DO", use_cache = TRUE ) # Dengue cases for two states with parallel processing df_dengue <- sus_data_import( uf = c("SP", "MG"), year = 2023, system = "SINAN-DENGUE", parallel = TRUE, workers = 3 ) # Hospitalizations with monthly specification df_hospital <- sus_data_import( uf = "SP", year = 2024, month = 1:6, # January to June system = "SIH-RD", verbose = TRUE ) # Force re-download ignoring cache df_births <- sus_data_import( uf = "BA", year = 2020:2022, system = "SINASC", use_cache = TRUE, force_redownload = TRUE # Refresh cached data ) ## End(Not run)
Renders a bubble or choropleth map showing the spatial distribution of
health events (counts or incidence rates) at the Brazilian municipal level.
Designed for data produced by sus_data_aggregate().
Bubble map (map_type = "bubble") places proportionally sized,
colour-encoded circles at each municipality centroid. State boundaries are
drawn as a background polygon layer.
Choropleth map (map_type = "choropleth") fills municipality polygons
downloaded via geobr::read_municipality(). Requires geobr and sf.
If these packages are unavailable the function falls back to a bubble map
with a warning.
sus_data_plot_aggregate_map( df, value_col = NULL, map_type = c("bubble", "choropleth", "quantile_choropleth"), rate_per_100k = FALSE, period = NULL, city = NULL, top_n = NULL, state_borders = TRUE, show_labels = TRUE, palette = "YlOrRd", log_scale = TRUE, title = NULL, subtitle = NULL, caption = NULL, theme_style = "publication", base_size = 11, interactive = FALSE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )sus_data_plot_aggregate_map( df, value_col = NULL, map_type = c("bubble", "choropleth", "quantile_choropleth"), rate_per_100k = FALSE, period = NULL, city = NULL, top_n = NULL, state_borders = TRUE, show_labels = TRUE, palette = "YlOrRd", log_scale = TRUE, title = NULL, subtitle = NULL, caption = NULL, theme_style = "publication", base_size = 11, interactive = FALSE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )
df |
A |
value_col |
Character. Name of the health-count column to map.
If |
map_type |
Character. |
rate_per_100k |
Logical. If |
period |
Date scalar or |
city |
Character vector of municipality names or 6-/7-digit IBGE codes.
When supplied, the map is restricted to those municipalities. Names are
resolved through |
top_n |
Integer. If supplied, only the top N municipalities by
|
state_borders |
Logical. Overlay state boundary polygons
(downloaded via |
show_labels |
Logical. Annotate capital cities with text labels
(bubble map only). Default |
palette |
Character. Colour palette for the fill / bubble fill scale.
Any |
log_scale |
Logical. Apply |
title |
Character. Map title. |
subtitle |
Character. Map subtitle. |
caption |
Character. Figure caption. |
theme_style |
Character. Reserved for future theme variants.
Currently only |
base_size |
Numeric. Base font size for |
interactive |
Logical. If |
use_cache |
Logical. Cache municipality metadata to disk.
Default |
cache_dir |
Character. Directory for the disk cache.
Default |
lang |
Character. Language for messages and axis labels:
|
verbose |
Logical. Print progress messages. Default |
A ggplot2 object (class "gg" / "ggplot"), or a plotly
object when interactive = TRUE. The function does not modify df
or advance the pipeline stage.
sus_data_aggregate(), sus_climate_plot_aggregate()
## Not run: library(climasus4r) # Monthly deaths by municipality df_agg <- sus_data_import(uf = "RN", year = 2022, system = "SIM-DO") |> sus_data_standardize() |> sus_data_aggregate(time_unit = "month", group_by = "codigo_municipio_residencia") # Default bubble map (Portuguese labels) sus_data_plot_aggregate_map(df_agg, lang = "pt") # Choropleth with incidence rate per 100k, English labels sus_data_plot_aggregate_map( df_agg, map_type = "choropleth", rate_per_100k = TRUE, palette = "Blues", lang = "en" ) # Interactive plotly bubble map sus_data_plot_aggregate_map(df_agg, interactive = TRUE, lang = "pt") ## End(Not run)## Not run: library(climasus4r) # Monthly deaths by municipality df_agg <- sus_data_import(uf = "RN", year = 2022, system = "SIM-DO") |> sus_data_standardize() |> sus_data_aggregate(time_unit = "month", group_by = "codigo_municipio_residencia") # Default bubble map (Portuguese labels) sus_data_plot_aggregate_map(df_agg, lang = "pt") # Choropleth with incidence rate per 100k, English labels sus_data_plot_aggregate_map( df_agg, map_type = "choropleth", rate_per_100k = TRUE, palette = "Blues", lang = "en" ) # Interactive plotly bubble map sus_data_plot_aggregate_map(df_agg, interactive = TRUE, lang = "pt") ## End(Not run)
Produces publication-quality time-series visualisations (epidemic curve,
seasonal boxplot, calendar heatmap, or annual trend) from a climasus_df
dataset at stage "aggregate" or later. Colour palettes are powered by
ggsci::ggsci (Lancet, NEJM, JCO, UChicago). An interactive plotly::plotly widget can
be returned with interactive = TRUE.
sus_data_plot_aggregate_ts( df, value_col = NULL, group_col = NULL, facet_col = NULL, facet_ncol = 3L, plot_type = c("epidemic", "seasonal", "heatmap", "trend"), smooth_method = "loess", smooth_span = 0.25, log_transform = FALSE, free_scales = TRUE, palette = "lancet", title = NULL, subtitle = NULL, caption = NULL, theme_style = "publication", date_labels = "%b/%y", year_breaks = "3 months", base_size = 11, interactive = FALSE, city = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )sus_data_plot_aggregate_ts( df, value_col = NULL, group_col = NULL, facet_col = NULL, facet_ncol = 3L, plot_type = c("epidemic", "seasonal", "heatmap", "trend"), smooth_method = "loess", smooth_span = 0.25, log_transform = FALSE, free_scales = TRUE, palette = "lancet", title = NULL, subtitle = NULL, caption = NULL, theme_style = "publication", date_labels = "%b/%y", year_breaks = "3 months", base_size = 11, interactive = FALSE, city = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", lang = "pt", verbose = TRUE )
df |
A |
value_col |
Character. Name of the outcome column to plot. If |
group_col |
Character. Optional column used for colour-grouping in
|
facet_col |
Character. Optional column for |
facet_ncol |
Integer. Number of facet columns. Default |
plot_type |
Character. One or more of |
smooth_method |
Character. Smoothing method for the |
smooth_span |
Numeric. Span for LOESS smoothing. Default |
log_transform |
Logical. Apply |
free_scales |
Logical. Allow free y-axis scales in faceted plots.
Default |
palette |
Character. Colour palette. One of |
title |
Character. Plot title. Auto-generated if |
subtitle |
Character. Plot subtitle. |
caption |
Character. Figure caption. |
theme_style |
Character. Reserved for future theme variants.
Currently only |
date_labels |
Character. |
year_breaks |
Character. |
base_size |
Numeric. Base font size for the ggplot2 theme. Default |
interactive |
Logical. Return a |
city |
Character vector of municipality names or 6-/7-digit IBGE codes.
When supplied, the plot is filtered to those municipalities before
rendering. Names are resolved through |
use_cache |
Logical. Cache municipality metadata to disk when city
filtering or municipality labels are needed. Default |
cache_dir |
Character. Directory for municipality metadata cache.
Default |
lang |
Character. Language for labels and messages: |
verbose |
Logical. Print progress messages. Default |
Invisibly returns the ggplot2 object (or plotly widget when
interactive = TRUE). Side effect: prints the plot in the active graphics
device.
Automatically adapts y-axis labels and titles to SINAN, SIM, SIH, SINASC, SIA, and CNES via outcome column auto-detection.
## Not run: # Epidemic curve, Portuguese labels sus_data_plot_aggregate_ts(df_agg, lang = "pt") # Seasonal boxplot, log-transformed sus_data_plot_aggregate_ts( df_agg, plot_type = "seasonal", log_transform = TRUE, lang = "en" ) # Calendar heatmap by group sus_data_plot_aggregate_ts( df_agg, plot_type = "heatmap", facet_col = "municipio", facet_ncol = 2L, lang = "pt" ) # Multi-panel: epidemic + trend sus_data_plot_aggregate_ts( df_agg, plot_type = c("epidemic", "trend"), lang = "en" ) # Interactive plotly widget sus_data_plot_aggregate_ts(df_agg, interactive = TRUE) ## End(Not run)## Not run: # Epidemic curve, Portuguese labels sus_data_plot_aggregate_ts(df_agg, lang = "pt") # Seasonal boxplot, log-transformed sus_data_plot_aggregate_ts( df_agg, plot_type = "seasonal", log_transform = TRUE, lang = "en" ) # Calendar heatmap by group sus_data_plot_aggregate_ts( df_agg, plot_type = "heatmap", facet_col = "municipio", facet_ncol = 2L, lang = "pt" ) # Multi-panel: epidemic + trend sus_data_plot_aggregate_ts( df_agg, plot_type = c("epidemic", "trend"), lang = "en" ) # Interactive plotly widget sus_data_plot_aggregate_ts(df_agg, interactive = TRUE) ## End(Not run)
Produces publication-quality tables, charts, and composite dashboards
summarising the demographic and climate-risk composition of any
standardised climasus_df dataset (SIM, SIH, SINAN, CNES, SIA, SINASC).
Visual style follows The Lancet / Nature Medicine guidelines.
Colour palettes are powered by ggsci::ggsci.
sus_data_plot_demographics( df, type = "table", var = NULL, time_unit = "month", fill_var = NULL, palette = "lancet", heatmap_row = NULL, heatmap_col = NULL, fill_metric = "pct_row", show_ci = FALSE, benchmark = NULL, interactive = FALSE, base_size = 11, lang = "pt", subtitle = NULL, caption = NULL, theme_style = "publication", caption_suffix = NULL, save_path = NULL, width = NULL, height = NULL, dpi = 300, verbose = TRUE, ... )sus_data_plot_demographics( df, type = "table", var = NULL, time_unit = "month", fill_var = NULL, palette = "lancet", heatmap_row = NULL, heatmap_col = NULL, fill_metric = "pct_row", show_ci = FALSE, benchmark = NULL, interactive = FALSE, base_size = 11, lang = "pt", subtitle = NULL, caption = NULL, theme_style = "publication", caption_suffix = NULL, save_path = NULL, width = NULL, height = NULL, dpi = 300, verbose = TRUE, ... )
df |
A |
type |
Character. Visualisation type. One of:
|
var |
Character. Demographic variable (required for |
time_unit |
Character. Temporal resolution for |
fill_var |
Character. Optional stratification variable for temporal
plots (e.g., |
palette |
Character. Colour palette powered by ggsci::ggsci. One of
|
heatmap_row |
Character. Row variable for |
heatmap_col |
Character. Column variable for |
fill_metric |
Character. What to show in each tile for
|
show_ci |
Logical. Add 95% Poisson confidence intervals in temporal
plots. Default |
benchmark |
Numeric named vector. Reference proportions for the
race-equity plot. If |
interactive |
Logical. Return interactive |
base_size |
Numeric. Base font size for ggplot2 theme. Default |
lang |
Character. Language for labels and messages. One of |
subtitle |
Character. Figure subtitle. |
caption |
Character. Figure caption. |
theme_style |
Character. Reserved for future theme variants.
Currently only |
caption_suffix |
Character. Additional text appended to the figure
caption (e.g., study period, DOI). Default |
save_path |
Character. File path to save output (PNG, PDF, SVG, or
HTML). Default |
width, height
|
Numeric. Output dimensions in inches. Defaults: |
dpi |
Numeric. Resolution for raster output. Default |
verbose |
Logical. Print progress messages. Default |
... |
Additional arguments passed to underlying plot helpers. |
Invisibly returns the primary plot or list of plots. Side effect: renders in the active graphics device (or interactive widget).
Automatically adapts column detection to SINAN, SIM, SIH, CNES, SIA, and
SINASC. Run sus_data_create_variables() before this function to generate
age_group, year, month, epidemiological_week, and
climate_risk_group.
When climate_risk_group is present (created by
sus_data_create_variables()), type = "climate" produces a combined
bar + seasonal heatmap designed for climate-health submissions to
The Lancet Planetary Health.
## Not run: # Age-sex pyramid (Lancet palette, Portuguese) sus_data_plot_demographics(df, type = "pyramid", lang = "pt") # Composite dashboard saved as PDF sus_data_plot_demographics( df, type = "dashboard", palette = "lancet", lang = "en", save_path = "figures/fig1_demographics.pdf", width = 12, height = 9 ) # Epidemic curve stratified by climate risk group (with CI) sus_data_plot_demographics( df, type = "temporal", time_unit = "epi_week", fill_var = "climate_risk_group", show_ci = TRUE, lang = "pt" ) # Race equity diverging plot sus_data_plot_demographics(df, type = "race_equity", lang = "pt") # Cross-demographic heatmap: age group x race, % within each age group sus_data_plot_demographics( df, type = "heatmap", heatmap_row = "age_group", heatmap_col = "race", fill_metric = "pct_row", lang = "pt" ) # Cross-demographic heatmap: education x climate risk (absolute counts) sus_data_plot_demographics( df, type = "heatmap", heatmap_row = "education", heatmap_col = "climate_risk", fill_metric = "count", palette = "nejm" ) ## End(Not run)## Not run: # Age-sex pyramid (Lancet palette, Portuguese) sus_data_plot_demographics(df, type = "pyramid", lang = "pt") # Composite dashboard saved as PDF sus_data_plot_demographics( df, type = "dashboard", palette = "lancet", lang = "en", save_path = "figures/fig1_demographics.pdf", width = 12, height = 9 ) # Epidemic curve stratified by climate risk group (with CI) sus_data_plot_demographics( df, type = "temporal", time_unit = "epi_week", fill_var = "climate_risk_group", show_ci = TRUE, lang = "pt" ) # Race equity diverging plot sus_data_plot_demographics(df, type = "race_equity", lang = "pt") # Cross-demographic heatmap: age group x race, % within each age group sus_data_plot_demographics( df, type = "heatmap", heatmap_row = "age_group", heatmap_col = "race", fill_metric = "pct_row", lang = "pt" ) # Cross-demographic heatmap: education x climate risk (absolute counts) sus_data_plot_demographics( df, type = "heatmap", heatmap_row = "education", heatmap_col = "climate_risk", fill_metric = "count", palette = "nejm" ) ## End(Not run)
Reads sus_meta processing history to identify which climasus4r pipeline
functions were applied, then produces a section-by-section quality
assessment covering completeness, demographic distributions, date
validity, ICD-10 codes, geographic coverage, and derived variables.
Returns an overall quality score (0-100) and supports four output formats.
sus_data_quality_report( df, output_format = "console", output_file = NULL, check_icd = TRUE, check_dates = TRUE, top_n = 10, lang = "pt", verbose = TRUE )sus_data_quality_report( df, output_format = "console", output_file = NULL, check_icd = TRUE, check_dates = TRUE, top_n = 10, lang = "pt", verbose = TRUE )
df |
A |
output_format |
Character. One of |
output_file |
Character. File path for |
check_icd |
Logical. Include ICD-10 quality section. Default |
check_dates |
Logical. Include date validation section. Default |
top_n |
Integer. Rows shown in frequency tables. Default |
lang |
Character. Output language: |
verbose |
Logical. Print progress messages. Default |
Invisibly returns a named list of quality metrics (always
available regardless of output_format):
$metaPipeline metadata from sus_meta
$pipelineFunctions detected in processing history
$overviewRow/column counts, duplicates, column types
$missingPer-column missing values with quality flags
$demographicsFrequency tables for sex, race, age, education
$datesDate range and validity per date column
$icdICD-10 frequency and validity
$geographicMunicipality and state coverage
$derivedPresence of expected derived variables
$scoreOverall quality score 0-100
## Not run: # Console report (default) sus_data_quality_report(df, lang = "pt") # gt table (for Quarto / R Markdown) sus_data_quality_report(df, output_format = "gt", lang = "en") # Save complete Markdown report sus_data_quality_report(df, output_format = "markdown", output_file = "reports/quality.md", lang = "pt") # Save HTML report sus_data_quality_report(df, output_format = "html", output_file = "reports/quality.html") ## End(Not run)## Not run: # Console report (default) sus_data_quality_report(df, lang = "pt") # gt table (for Quarto / R Markdown) sus_data_quality_report(df, output_format = "gt", lang = "en") # Save complete Markdown report sus_data_quality_report(df, output_format = "markdown", output_file = "reports/quality.md", lang = "pt") # Save HTML report sus_data_quality_report(df, output_format = "html", output_file = "reports/quality.html") ## End(Not run)
Smartly reads one or multiple health data files exported by sus_data_export().
Supports automatic format detection, batch processing, parallel execution, spatial data,
metadata loading, and data validation.
sus_data_read( path, format = NULL, parallel = FALSE, workers = 4, read_metadata = FALSE, lang = "pt", verbose = TRUE )sus_data_read( path, format = NULL, parallel = FALSE, workers = 4, read_metadata = FALSE, lang = "pt", verbose = TRUE )
path |
Character vector of file paths, or a single directory path. If a directory is provided, all matching files will be read. |
format |
Character string specifying the input format. Options: |
parallel |
Logical. If |
workers |
Integer. Number of parallel workers when |
read_metadata |
Logical. If |
lang |
Character string specifying the language for messages. Options:
|
verbose |
Logical. If |
Batch Processing: Pass a vector of file paths or a directory path to read multiple files at once. All files are automatically combined into a single object.
Parallel Processing:
When parallel = TRUE, files are read simultaneously using future.apply.
This significantly speeds up batch reads of large files.
Format Detection:
Automatically detects format from file extension. For .parquet files,
automatically determines if it's GeoParquet (spatial) or regular Parquet.
Memory Efficiency: For very large datasets (>50 GB), consider using chunked processing or reading files individually instead of batch mode.
A data frame or sf object (for spatial data) containing the loaded data.
For batch reads, all files are combined with dplyr::bind_rows().
Metadata is attached as attributes:
Single file: attr(df, "metadata")
Batch: attr(df, "batch_metadata") (list of metadata from each file)
Batch: attr(df, "n_files_combined") (number of files)
## Not run: library(climasus4r) # Single file df <- sus_data_read("output/data.parquet") # Multiple files (vector) df <- sus_data_read(c("output/2020.parquet", "output/2021.parquet")) # Directory (all Parquet files) df <- sus_data_read("output/", format = "parquet") # Parallel batch read df <- sus_data_read("output/", format = "dbf", parallel = TRUE, workers = 6) # Access batch metadata batch_meta <- attr(df, "batch_metadata") n_files <- attr(df, "n_files_combined") ## End(Not run)## Not run: library(climasus4r) # Single file df <- sus_data_read("output/data.parquet") # Multiple files (vector) df <- sus_data_read(c("output/2020.parquet", "output/2021.parquet")) # Directory (all Parquet files) df <- sus_data_read("output/", format = "parquet") # Parallel batch read df <- sus_data_read("output/", format = "dbf", parallel = TRUE, workers = 6) # Access batch metadata batch_meta <- attr(df, "batch_metadata") n_files <- attr(df, "n_files_combined") ## End(Not run)
This function standardizes column names and categorical values in SUS datasets, ensuring consistency across different years and versions. It supports three languages: English (en), Portuguese (pt), and Spanish (es).
sus_data_standardize( df, lang = "pt", translate_columns = TRUE, standardize_values = TRUE, keep_original = FALSE, backend = "arrow", verbose = TRUE )sus_data_standardize( df, lang = "pt", translate_columns = TRUE, standardize_values = TRUE, keep_original = FALSE, backend = "arrow", verbose = TRUE )
df |
A |
lang |
Character. Output language for column names and values. Options: "en" (English), "pt" (Portuguese, Default), "es" (Spanish). |
translate_columns |
Logical. If TRUE, translates column names. Default is TRUE. |
standardize_values |
Logical. If TRUE, standardizes categorical values. Default is TRUE. |
keep_original |
Logical. If TRUE, keeps original columns alongside standardized ones. Default is FALSE. |
backend |
Character string specifying the data processing backend.
Use
If not specified, the function may automatically choose the backend based on the input data type. |
verbose |
Logical. If TRUE, prints a report of standardization actions. Default is TRUE. |
The function builds upon the preprocessing done by microdatasus, adding an
additional layer of standardization specifically designed for climate-health
research workflows.
A data.frame with standardized column names and values in the specified language.
Brazilian Ministry of Health. DATASUS. http://datasus.saude.gov.br
SALDANHA, Raphael de Freitas; BASTOS, Ronaldo Rocha; BARCELLOS, Christovam. Microdatasus: pacote para download e pre-processamento de microdados do Departamento de Informatica do SUS (DATASUS). Cad. Saude Publica, Rio de Janeiro , v. 35, n. 9, e00032419, 2019. Available from https://doi.org/10.1590/0102-311x00032419.
## Not run: # Standardize to English (default) df_en <- sus_data_standardize(df_raw, lang = "en") # Standardize to Portuguese df_pt <- sus_data_standardize(df_raw, lang = "pt") # Standardize to Spanish df_es <- sus_data_standardize(df_raw, lang = "es") # Keep original columns for comparison df_both <- sus_data_standardize( df_raw, lang = "pt", keep_original = TRUE ) # Only translate column names (not values) df_cols_only <- sus_data_standardize( df_raw, lang = "en", translate_columns = TRUE, standardize_values = FALSE ) # Complete pipeline df_analysis_ready <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") |> sus_data_clean_encoding() |> sus_data_standardize(lang = "pt") ## End(Not run)## Not run: # Standardize to English (default) df_en <- sus_data_standardize(df_raw, lang = "en") # Standardize to Portuguese df_pt <- sus_data_standardize(df_raw, lang = "pt") # Standardize to Spanish df_es <- sus_data_standardize(df_raw, lang = "es") # Keep original columns for comparison df_both <- sus_data_standardize( df_raw, lang = "pt", keep_original = TRUE ) # Only translate column names (not values) df_cols_only <- sus_data_standardize( df_raw, lang = "en", translate_columns = TRUE, standardize_values = FALSE ) # Complete pipeline df_analysis_ready <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") |> sus_data_clean_encoding() |> sus_data_standardize(lang = "pt") ## End(Not run)
Evaluates the quality of daily health event time series at the municipal level, producing per-municipality flags for:
sus_data_ts_quality( data, outcome_col = "n_obitos", muni_col = "code_muni", date_col = "date", min_completeness = 0.9, max_gap = 7L, break_alpha = 0.05, max_outlier_months = 3L, lang = "pt", verbose = TRUE )sus_data_ts_quality( data, outcome_col = "n_obitos", muni_col = "code_muni", date_col = "date", min_completeness = 0.9, max_gap = 7L, break_alpha = 0.05, max_outlier_months = 3L, lang = "pt", verbose = TRUE )
data |
A |
outcome_col |
Character. Name of the daily count column.
Default: |
muni_col |
Character. Name of the municipality identifier column.
Default: |
date_col |
Character. Name of the date column. Default: |
min_completeness |
Numeric (0-1). Minimum completeness to recommend
inclusion. Default: |
max_gap |
Integer. Maximum tolerated consecutive zero/missing days
before flagging a temporal gap. Default: |
break_alpha |
Numeric. Significance level for structural break test.
Default: |
max_outlier_months |
Integer. Maximum number of outlier months allowed
before exclusion. Default: |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
Completeness: fraction of expected days with non-missing records.
Structural breaks: abrupt level shifts detectable by the CUSUM-based
Zeileis et al. (2002) test (requires the strucchange package).
Monthly outliers: months with counts > Q3 + 1.5 x IQR (Tukey fence).
Temporal gaps: runs of consecutive days with zero or missing counts
longer than max_gap.
A composite inclusion score (0-100) and a binary include recommendation
are returned, matching the exclusion criteria used in large Brazilian
heat-wave studies (Lowe et al. 2021, Anjos & Targino 2023).
A climasus_ts_quality list with:
$flagsTibble (one row per municipality) with columns:
muni_col, n_obs, n_expected, completeness, has_break,
break_pval, n_outlier_months, n_gaps_gt{max_gap}d, score,
include.
$recommend_includeCharacter vector of municipality codes recommended for inclusion.
$recommend_excludeCharacter vector of municipality codes recommended for exclusion, with reason.
$paramsList of QC parameters used.
Zeileis, A., Leisch, F., Hornik, K., & Kleiber, C. (2002). strucchange: An R Package for Testing for Structural Change in Linear Regression Models. Journal of Statistical Software, 7(2). doi:10.18637/jss.v007.i02
sus_data_aggregate(), sus_mod_casecrossover(), sus_mod_dlnm()
## Not run: qc <- sus_data_ts_quality( df_agg, outcome_col = "n_obitos", min_completeness = 0.90, max_gap = 7L ) print(qc) # Filter series to include only QC-passing municipalities df_clean <- df_agg[df_agg$code_muni %in% qc$recommend_include, ] ## End(Not run)## Not run: qc <- sus_data_ts_quality( df_agg, outcome_col = "n_obitos", min_completeness = 0.90, max_gap = 7L ) print(qc) # Filter series to include only QC-passing municipalities df_clean <- df_agg[df_agg$code_muni %in% qc$recommend_include, ] ## End(Not run)
sus_grid_chirps() downloads CHIRPS v2.0 precipitation data, crops it to
Brazil, spatially aggregates to municipalities, and returns a climasus_df
compatible with sus_mod_dlnm() and sus_climate_anomaly().
CHIRPS (Climate Hazards Group InfraRed Precipitation with Station data) is a
quasi-global, 0.05 (~5 km) daily rainfall dataset from UCSB CHC
covering 1981 to present. It combines satellite imagery with station data and
is considered the best freely available high-resolution rainfall product for
Brazil — particularly for leptospirosis, diarrheal disease, and dengue
analyses where precipitation is the key exposure.
No authentication is required.
sus_grid_chirps( resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/chirps", lang = "pt", verbose = TRUE )sus_grid_chirps( resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/chirps", lang = "pt", verbose = TRUE )
resolution |
Character. Temporal resolution of source files:
|
years |
Integer vector. Years to download. Coverage: 1981 to present
for daily/monthly; 1981–2024 for annual. |
months |
Integer vector (1–12). Months to include for daily and monthly
resolutions. Ignored for annual. Default |
municipalities |
An |
agg_fun |
Character. Spatial aggregation function for
|
crop_brazil |
Logical. Crop global rasters to Brazil's bounding box
before aggregation. Reduces memory usage significantly. Default |
use_cache |
Logical. Reuse previously downloaded raster files and
aggregated Parquet caches. Default |
cache_dir |
Character. Root cache directory.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
If municipalities is provided: a climasus_df with columns
code_muni (character), date (Date), and rainfall_chirps_mm
(numeric). Metadata: stage = "climate", type = "chirps".
If municipalities = NULL: a named character vector of paths to
the cached GeoTIFF/gz files.
Daily: mm/day
Monthly: mm/month (cumulative)
Annual: mm/year (cumulative)
CHIRPS missing/no-data value (-9999) is automatically converted to NA.
Funk, C. et al. (2015). The climate hazards infrared precipitation with
stations — a new environmental record for monitoring extremes.
Scientific Data, 2, 150066. doi:10.1038/sdata.2015.66
Data: https://data.chc.ucsb.edu/products/CHIRPS-2.0/
Spatial aggregation requires terra and exactextractr (both in
Suggests). Install with install.packages(c("terra", "exactextractr")).
sus_grid_era5(), sus_climate_anomaly(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Monthly rainfall for Mato Grosso, 2020 chirps <- sus_grid_chirps( resolution = "monthly", years = 2020, municipalities = mt_mun, lang = "pt" ) sus_meta(chirps, "stage") # "climate" sus_meta(chirps, "type") # "chirps" # Daily rainfall, fire season chirps_daily <- sus_grid_chirps( resolution = "daily", years = 2020, months = 7:9, municipalities = mt_mun, agg_fun = "mean", lang = "en" ) # Annual totals for all Brazil (no spatial aggregation) paths <- sus_grid_chirps( resolution = "annual", years = 2018:2022 ) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Monthly rainfall for Mato Grosso, 2020 chirps <- sus_grid_chirps( resolution = "monthly", years = 2020, municipalities = mt_mun, lang = "pt" ) sus_meta(chirps, "stage") # "climate" sus_meta(chirps, "type") # "chirps" # Daily rainfall, fire season chirps_daily <- sus_grid_chirps( resolution = "daily", years = 2020, months = 7:9, municipalities = mt_mun, agg_fun = "mean", lang = "en" ) # Annual totals for all Brazil (no spatial aggregation) paths <- sus_grid_chirps( resolution = "annual", years = 2018:2022 ) ## End(Not run)
sus_grid_era5() downloads pre-processed ERA5-Land daily climate aggregates
for Latin America from Zenodo and, optionally, spatially aggregates them to
Brazilian municipalities. No API key is required.
The data source is the ERA5-Land Daily Aggregates for Latin America project (Saldanha, rfsaldanha.github.io), which provides NetCDF files (one per variable × month × year) at ~10 km spatial resolution for 1950–2025. Files are hosted on Zenodo under CC-BY 4.0.
When municipalities is provided, the function returns a climasus_df at
stage = "climate", type = "era5_land" — directly compatible with
sus_climate_anomaly(), sus_climate_aggregate(), and sus_mod_dlnm().
sus_grid_era5( years, months = 1:12, vars = c("t2m", "tp"), municipalities = NULL, agg_fun = "mean", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/era5", parallel = FALSE, workers = 2, lang = "pt", verbose = TRUE )sus_grid_era5( years, months = 1:12, vars = c("t2m", "tp"), municipalities = NULL, agg_fun = "mean", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/era5", parallel = FALSE, workers = 2, lang = "pt", verbose = TRUE )
years |
Numeric vector of years to import. Must be between 1950 and 2025.
Example: |
months |
Integer vector of months to import (1–12). Default: |
vars |
Character vector of variable aliases to download. Allowed values:
Default: |
municipalities |
An |
agg_fun |
Character. Spatial aggregation function applied over raster
pixels within each polygon. Any function supported by
|
use_cache |
Logical. If |
cache_dir |
Character. Directory for cached NetCDF files.
Default: |
parallel |
Logical. If |
workers |
Integer. Number of parallel workers when |
lang |
Character. Language for messages: |
verbose |
Logical. If |
If municipalities is provided: a climasus_df tibble with columns
code_muni (character), date (Date), and one column per requested
variable (e.g., tair_dry_bulb_c, rainfall_mm). Metadata:
stage = "climate", type = "era5_land".
If municipalities = NULL: a named character vector of paths to
the downloaded NetCDF files (named by "{year}_{month}_{var}").
Saldanha, R. ERA5-Land Daily Aggregates for Latin America (1950–2025). Zenodo. https://zenodo.org/doi/10.5281/zenodo.10013254. CC-BY 4.0.
Temperature (K → °C): subtract 273.15
Precipitation (m → mm): multiply by 1000
Pressure (Pa → hPa): divide by 100
Wind components (m/s): no conversion needed
sus_climate_anomaly(), sus_climate_aggregate(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Temperature and precipitation for Mato Grosso, Q1 2020 era5 <- sus_grid_era5( years = 2020, months = 1:3, vars = c("t2m", "tp"), municipalities = mt_mun, lang = "pt" ) sus_meta(era5, "stage") # "climate" sus_meta(era5, "type") # "era5_land" # All variables, no spatial aggregation (returns file paths) paths <- sus_grid_era5(years = 2020, months = 1, vars = "all") ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Temperature and precipitation for Mato Grosso, Q1 2020 era5 <- sus_grid_era5( years = 2020, months = 1:3, vars = c("t2m", "tp"), municipalities = mt_mun, lang = "pt" ) sus_meta(era5, "stage") # "climate" sus_meta(era5, "type") # "era5_land" # All variables, no spatial aggregation (returns file paths) paths <- sus_grid_era5(years = 2020, months = 1, vars = "all") ## End(Not run)
sus_grid_fires() downloads fire hotspot (active fire) data from INPE
Queimadas or NASA FIRMS, optionally aggregates counts and Fire Radiative
Power (FRP) to Brazilian municipalities, and returns a climasus_df
compatible with sus_mod_dlnm() and sus_climate_anomaly().
Fire data is critical for respiratory health analyses in Brazil: smoke from agricultural burning (cerrado, cana-de-acucar) and deforestation fires (Amazonia) are associated with acute respiratory outcomes in SIH/SINAN data.
Sources available:
"inpe" (default) — INPE Queimadas portal. No authentication.
Historical data from 1998 to present. Brazil only.
DOI: doi:10.2312/inpe.2022.009
"firms_modis" — NASA FIRMS MODIS Collection 6.1.
Requires a free MAP KEY from
https://firms.modaps.eosdis.nasa.gov/api/map_key/.
Global, 1 km resolution, 2000 to present.
"firms_viirs" — NASA FIRMS VIIRS SNPP.
Same key as FIRMS MODIS. 375 m resolution, 2012 to present.
sus_grid_fires( years, months = 1:12, uf = NULL, bbox = NULL, source = c("inpe", "firms_modis", "firms_viirs"), municipalities = NULL, agg_fun = "count", biome = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/fires", firms_key = NULL, lang = "pt", verbose = TRUE )sus_grid_fires( years, months = 1:12, uf = NULL, bbox = NULL, source = c("inpe", "firms_modis", "firms_viirs"), municipalities = NULL, agg_fun = "count", biome = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/fires", firms_key = NULL, lang = "pt", verbose = TRUE )
years |
Numeric vector of years. INPE: 1998–present. FIRMS MODIS: 2000–present. FIRMS VIIRS: 2012–present. |
months |
Integer vector (1–12). Default |
uf |
Character vector of state codes (e.g., |
bbox |
Numeric vector |
source |
Character. Data source: |
municipalities |
An |
agg_fun |
Character. Aggregation strategy when |
biome |
Character vector. INPE biome filter. Allowed values:
|
use_cache |
Logical. Reuse previously downloaded CSV/JSON files.
Default |
cache_dir |
Character. Root cache directory.
Default |
firms_key |
Character. NASA FIRMS MAP KEY.
Defaults to |
lang |
Character. Message language: |
verbose |
Logical. Print progress. Default |
If municipalities is provided: a climasus_df with columns
date (Date), code_muni (character), n_fires (integer count of
hotspots), and frp_mean (mean Fire Radiative Power in MW,
NA when not available). Metadata: stage = "climate",
type = "fires".
If municipalities = NULL: a climasus_df with raw fire point
columns: date, lat, lon, frp, biome, estado, source.
Queries https://queimadas.dgi.inpe.br/api/focos/ monthly. Each monthly
request is cached as a JSON file. Large states in fire-season months may
return truncated results due to the API's record limit; use uf to
narrow the query when needed.
Queries https://firms.modaps.eosdis.nasa.gov/api/area/csv/{key}/{product}/{bbox}/10/{date}
in 10-day chunks (maximum allowed per request). A free MAP KEY is required
and must be activated at https://firms.modaps.eosdis.nasa.gov/api/map_key/.
sus_grid_pollution_cams(), sus_climate_anomaly(),
sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # INPE fire count for Mato Grosso municipalities, fire season 2020 fires <- sus_grid_fires( years = 2020, months = 7:10, uf = "MT", municipalities = mt_mun, lang = "pt" ) sus_meta(fires, "stage") # "climate" sus_meta(fires, "type") # "fires" # Raw fire points for Amazonia, no aggregation fires_pts <- sus_grid_fires( years = 2022, months = 8, biome = "Amazonia", lang = "en" ) # FIRMS MODIS with API key Sys.setenv(FIRMS_MAP_KEY = "my_key") fires_firms <- sus_grid_fires( years = 2023, months = 9, uf = "MT", source = "firms_modis", municipalities = mt_mun ) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # INPE fire count for Mato Grosso municipalities, fire season 2020 fires <- sus_grid_fires( years = 2020, months = 7:10, uf = "MT", municipalities = mt_mun, lang = "pt" ) sus_meta(fires, "stage") # "climate" sus_meta(fires, "type") # "fires" # Raw fire points for Amazonia, no aggregation fires_pts <- sus_grid_fires( years = 2022, months = 8, biome = "Amazonia", lang = "en" ) # FIRMS MODIS with API key Sys.setenv(FIRMS_MAP_KEY = "my_key") fires_firms <- sus_grid_fires( years = 2023, months = 9, uf = "MT", source = "firms_modis", municipalities = mt_mun ) ## End(Not run)
sus_grid_join() merges the municipality × date output of any
sus_grid_*() function (ERA5, CHIRPS, GHAP, CAMS, fires, PRODES, …) with
a health climasus_df produced by sus_spatial_join() or
sus_data_aggregate(). The result is a single climasus_df at
stage = "climate" ready for sus_mod_dlnm(), sus_climate_anomaly(),
and sus_mod_vulnerability_index().
This function is the bridge between the gridded environmental pipeline
(sus_grid_*) and the health pipeline (sus_data_import → … →
sus_spatial_join), equivalent to the role sus_climate_aggregate() plays
for station-based INMET data.
sus_grid_join( health_data, grid_data, by = c("code_muni", "date"), type_out = NULL, lang = "pt", verbose = TRUE )sus_grid_join( health_data, grid_data, by = c("code_muni", "date"), type_out = NULL, lang = "pt", verbose = TRUE )
health_data |
A |
grid_data |
A |
by |
Character vector. Join key columns. Default |
type_out |
Character. Overrides |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
A climasus_df with all columns from health_data plus the
environmental variable columns from grid_data. Metadata:
stage = "climate", type inherited from grid_data (or type_out).
Rows from health_data with no matching grid row receive NA for grid
columns.
If health_data has monthly dates (YYYY-MM-01) and grid_data has daily
dates, the join will produce NAs for most rows. In that case, first
aggregate grid_data to monthly resolution with
sus_climate_aggregate() or by passing by = c("code_muni") (annual
grid data only) or summarising manually before calling sus_grid_join().
sus_grid_era5(), sus_grid_chirps(), sus_grid_fires(),
sus_grid_prodes(), sus_climate_aggregate(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Health data (SIH respiratory hospitalisations) sih_agg <- sus_data_import(system = "SIH", years = 2020, uf = "MT") |> sus_data_clean_encoding() |> sus_data_standardize() |> sus_data_filter_cid(cid_group = "respiratorio") |> sus_data_aggregate() |> sus_spatial_join(municipalities = mt_mun) # Gridded climate data era5 <- sus_grid_era5( years = 2020, municipalities = mt_mun, vars = c("t2m", "tp") ) # Join: one step to connect health + climate combined <- sus_grid_join(sih_agg, era5) sus_meta(combined, "stage") # "climate" sus_meta(combined, "type") # "era5_land" # Annual deforestation joined to monthly health data (no date in by) prodes <- sus_grid_prodes(years = 2020, biomes = "Amazon", uf = "MT", municipalities = mt_mun) combined2 <- sus_grid_join(sih_agg, prodes, by = "code_muni") ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Health data (SIH respiratory hospitalisations) sih_agg <- sus_data_import(system = "SIH", years = 2020, uf = "MT") |> sus_data_clean_encoding() |> sus_data_standardize() |> sus_data_filter_cid(cid_group = "respiratorio") |> sus_data_aggregate() |> sus_spatial_join(municipalities = mt_mun) # Gridded climate data era5 <- sus_grid_era5( years = 2020, municipalities = mt_mun, vars = c("t2m", "tp") ) # Join: one step to connect health + climate combined <- sus_grid_join(sih_agg, era5) sus_meta(combined, "stage") # "climate" sus_meta(combined, "type") # "era5_land" # Annual deforestation joined to monthly health data (no date in by) prodes <- sus_grid_prodes(years = 2020, biomes = "Amazon", uf = "MT", municipalities = mt_mun) combined2 <- sus_grid_join(sih_agg, prodes, by = "code_muni") ## End(Not run)
Adds a zona_koppen column to a climasus_df (or plain data.frame) with
municipality-level Koppen-Geiger climate classification following
Alvares et al. (2013), who produced the first high-resolution (1 km) Koppen
map for Brazil.
sus_grid_koppen( data, mode = "approx", koppen_sf = NULL, as_factor = TRUE, lang = "pt", verbose = TRUE )sus_grid_koppen( data, mode = "approx", koppen_sf = NULL, as_factor = TRUE, lang = "pt", verbose = TRUE )
data |
A |
mode |
Character. Assignment mode: |
koppen_sf |
An |
as_factor |
Logical. Return |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
Two assignment modes are available:
"approx" (default): rule-based assignment from municipality centroid
coordinates stored in the built-in municipio_meta table. Fast and
dependency-free, with ~85% accuracy at the municipal level.
"exact": spatial join between municipality centroids and a user-
supplied sf polygon layer (koppen_sf). Produces exact results when the
original Alvares et al. (2013) shapefile is provided.
The input object with an additional column zona_koppen. If the
input was a climasus_df, the returned object preserves its class and
sus_meta attribute with the history updated.
Tropical humid (equatorial) – Amazon / NE coast.
Tropical monsoon – North / Center-West.
Tropical summer dry – NE coast.
Tropical winter dry (savanna) – Central Brazil.
Hot semi-arid – NE sertao.
Subtropical humid – South / coastal SE.
Subtropical winter dry – SE plateau / Center-West uplands.
Alvares, C.A., Stape, J.L., Sentelhas, P.C., Goncalves, J.L.M., & Sparovek, G. (2013). Koppen's climate classification map for Brazil. Meteorologische Zeitschrift, 22(6), 711-728. doi:10.1127/0941-2948/2013/0507
sus_grid_era5(), sus_mod_casecrossover(), sus_mod_dlnm()
## Not run: library(climasus4r) # With a climasus_df that has code_muni df_with_koppen <- sus_grid_koppen(df_aggregated, mode = "approx") table(df_with_koppen$zona_koppen) # Exact mode with Alvares et al. 2013 shapefile library(sf) kop_sf <- sf::read_sf("koppen_brazil_alvares2013.shp") names(kop_sf)[names(kop_sf) == "zone"] <- "koppen" # rename if needed df_exact <- sus_grid_koppen(df_aggregated, mode = "exact", koppen_sf = kop_sf) ## End(Not run)## Not run: library(climasus4r) # With a climasus_df that has code_muni df_with_koppen <- sus_grid_koppen(df_aggregated, mode = "approx") table(df_with_koppen$zona_koppen) # Exact mode with Alvares et al. 2013 shapefile library(sf) kop_sf <- sf::read_sf("koppen_brazil_alvares2013.shp") names(kop_sf)[names(kop_sf) == "zone"] <- "koppen" # rename if needed df_exact <- sus_grid_koppen(df_aggregated, mode = "exact", koppen_sf = kop_sf) ## End(Not run)
sus_grid_pdsi() downloads Palmer Drought Severity Index (PDSI) data,
crops it to Brazil, spatially aggregates to municipalities, and returns a
climasus_df compatible with sus_mod_dlnm() and sus_climate_anomaly().
PDSI (Palmer, 1965) quantifies cumulative moisture departures relative to local climate normals using a two-layer soil water balance model. Values range from approximately -10 (extreme drought) to +10 (extreme wet), with operational categories at -2 (moderate drought) to -4 (extreme drought). Health applications in Brazil:
Drought (PDSI < -2): malnutrition, diarrheal disease, mental health stress, vector-borne disease in semi-arid Northeast and Amazônia
Wet periods (PDSI > 2): leptospirosis, hepatitis A, flooding
Available sources:
"terraclimate" (default): TerraClimate monthly PDSI (Abatzoglou
et al., 2018; University of Idaho). Resolution 1/24° (~4 km), 1950–2025,
WGS84, no authentication. One NetCDF file (~165 MB) per year.
"noaa_psl": Dai (2011) self-calibrated PDSI from NOAA Physical
Sciences Laboratory. Resolution 2.5°, 1850–2018, single global file
(~40 MB). Coarser but longer record.
sus_grid_pdsi( years = NULL, months = 1:12, source = c("terraclimate", "noaa_psl"), municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/pdsi", lang = "pt", verbose = TRUE )sus_grid_pdsi( years = NULL, months = 1:12, source = c("terraclimate", "noaa_psl"), municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/pdsi", lang = "pt", verbose = TRUE )
years |
Integer vector. Years to download.
TerraClimate: 1950–2025. NOAA PSL: 1850–2018.
|
months |
Integer vector (1–12). Months to include. Default |
source |
Character. Data source: |
municipalities |
An |
agg_fun |
Character. Spatial aggregation for
|
crop_brazil |
Logical. Crop global rasters to Brazil's bounding box.
Default |
use_cache |
Logical. Reuse cached NetCDF files and Parquet results.
Default |
cache_dir |
Character. Root cache directory.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
If municipalities is provided: a climasus_df with columns
code_muni, date (Date, first day of month), and pdsi (numeric,
unitless). Metadata: stage = "climate", type = "pdsi".
If municipalities = NULL: a named character vector of cached
NetCDF file paths.
PDSI >= +4.0 : Extremely wet PDSI +3.0 to +3.99 : Very wet PDSI +2.0 to +2.99 : Moderately wet PDSI -1.99 to +1.99 : Near normal PDSI -2.0 to -2.99 : Moderate drought (D1) PDSI -3.0 to -3.99 : Severe drought (D2) PDSI <= -4.0 : Extreme drought (D3-D4)
TerraClimate: Abatzoglou, J.T. et al. (2018). TerraClimate, a high- resolution global dataset of monthly climate and climatic water balance from 1958–2015. Scientific Data, 5, 170191. doi:10.1038/sdata.2017.191. URL: https://climate.northwestknowledge.net/TERRACLIMATE-DATA/
NOAA PSL: Dai, A. (2011). Characteristics and trends in various forms of the PDSI during 1900–2008. J. Geophys. Res., 116, D12115. doi:10.1029/2010JD015541. URL: https://downloads.psl.noaa.gov/Datasets/dai_pdsi/
terra and exactextractr (both in Suggests) are required when
municipalities is provided.
sus_climate_compute_spi(), sus_climate_compute_spei(),
sus_grid_chirps(), sus_grid_join(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # TerraClimate PDSI for Mato Grosso, 2015-2022 pdsi_mt <- sus_grid_pdsi( years = 2015:2022, months = 1:12, municipalities = mt_mun, lang = "pt" ) sus_meta(pdsi_mt, "stage") # "climate" sus_meta(pdsi_mt, "type") # "pdsi" # Longer history with NOAA PSL (2.5 deg) pdsi_hist <- sus_grid_pdsi( years = 1960:2018, source = "noaa_psl", municipalities = mt_mun, lang = "en" ) # Join to health data for DLNM combined <- sus_grid_join(sih_mt, pdsi_mt) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # TerraClimate PDSI for Mato Grosso, 2015-2022 pdsi_mt <- sus_grid_pdsi( years = 2015:2022, months = 1:12, municipalities = mt_mun, lang = "pt" ) sus_meta(pdsi_mt, "stage") # "climate" sus_meta(pdsi_mt, "type") # "pdsi" # Longer history with NOAA PSL (2.5 deg) pdsi_hist <- sus_grid_pdsi( years = 1960:2018, source = "noaa_psl", municipalities = mt_mun, lang = "en" ) # Join to health data for DLNM combined <- sus_grid_join(sih_mt, pdsi_mt) ## End(Not run)
sus_grid_pollution_cams() downloads pre-processed CAMS (Copernicus
Atmosphere Monitoring Service) daily pollution data for Brazilian
municipalities from Zenodo. No API key is required.
Data cover six pollutants — PM2.5, PM10, CO, O3, NO2 and SO2 — aggregated to daily means/maxima/minima per municipality from 2003 to 2024. Files are hosted on Zenodo (CC-BY) as Parquet and are downloaded once and cached locally.
The return value is a climasus_df at stage = "climate",
type = "pollution_cams", directly compatible with
sus_climate_anomaly(), sus_climate_aggregate(), and sus_mod_dlnm().
sus_grid_pollution_cams( pollutants = c("pm25", "pm10"), metric = "mean", years = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/cams", lang = "pt", verbose = TRUE )sus_grid_pollution_cams( pollutants = c("pm25", "pm10"), metric = "mean", years = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/cams", lang = "pt", verbose = TRUE )
pollutants |
Character vector. Pollutants to include. Allowed values:
|
metric |
Character. Daily aggregation statistic. One of:
|
years |
Integer vector. Years to include (2003–2024). |
use_cache |
Logical. Re-use previously downloaded Parquet files.
Default |
cache_dir |
Character. Directory for cached Parquet files.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
A climasus_df tibble with columns:
code_muni — 7-digit IBGE municipality code (character).
date — Date.
{pollutant}_{metric} — one numeric column per requested
pollutant × metric combination (e.g. pm25_mean, no2_max).
Metadata: stage = "climate", type = "pollution_cams".
Saldanha, R. et al. CAMS pollution daily averages for Brazilian
municipalities (2003–2024). Zenodo. CC-BY 4.0.
PM2.5: doi:10.5281/zenodo.16374139 |
PM10: doi:10.5281/zenodo.16419737 |
CO: doi:10.5281/zenodo.18641834 |
O3: doi:10.5281/zenodo.18641945 |
NO2: doi:10.5281/zenodo.18642048 |
SO2: doi:10.5281/zenodo.18642198
PM2.5, PM10, O3, NO2, SO2: µg/m³
CO: ppm
sus_climate_anomaly(), sus_climate_aggregate(), sus_mod_dlnm()
## Not run: # PM2.5 and NO2 daily means for 2019-2022 cams <- sus_grid_pollution_cams( pollutants = c("pm25", "no2"), metric = "mean", years = 2019:2022, lang = "pt" ) sus_meta(cams, "stage") # "climate" sus_meta(cams, "type") # "pollution_cams" # All pollutants, all metrics, all years cams_full <- sus_grid_pollution_cams( pollutants = "all", metric = "all", lang = "en" ) ## End(Not run)## Not run: # PM2.5 and NO2 daily means for 2019-2022 cams <- sus_grid_pollution_cams( pollutants = c("pm25", "no2"), metric = "mean", years = 2019:2022, lang = "pt" ) sus_meta(cams, "stage") # "climate" sus_meta(cams, "type") # "pollution_cams" # All pollutants, all metrics, all years cams_full <- sus_grid_pollution_cams( pollutants = "all", metric = "all", lang = "en" ) ## End(Not run)
sus_grid_pollution_ghap() downloads, crops, spatially aggregates, and
caches GHAP (GlobalHighAirPollutants) raster data to Brazilian
municipalities. No API key is required.
GHAP provides AI-generated, seamless ground-level air pollutant fields at 1 km (PM2.5, CO) and 10 km (O3) resolution. Files are downloaded as NetCDF from Zenodo, cropped to Brazil, aggregated with area-weighted extraction, and the result is stored as a Parquet cache for fast subsequent access.
Available pollutants and temporal coverage:
PM2.5 ("pm25") — daily, monthly & annual, 2017–2022, 1 km,
O3 ("o3") — annual only, 2000–2020, 10 km, ppb
CO ("co") — annual only, 2019–2022, 1 km, mg/m
NO2 ("no2") — data not yet publicly released
When municipalities is provided the function returns a climasus_df at
stage = "climate", type = "pollution_ghap", compatible with
sus_climate_anomaly(), sus_climate_aggregate(), and sus_mod_dlnm().
sus_grid_pollution_ghap( pollutants = "pm25", resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/ghap", lang = "pt", verbose = TRUE )sus_grid_pollution_ghap( pollutants = "pm25", resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/ghap", lang = "pt", verbose = TRUE )
pollutants |
Character vector. Pollutants to download.
Accepted: |
resolution |
Character. Temporal aggregation of source files.
One of
O3 and CO automatically fall back to |
years |
Integer vector. Years to download. Availability depends on pollutant and resolution:
|
months |
Integer vector (1–12). Months to include when
|
municipalities |
An |
agg_fun |
Character. Spatial aggregation function applied by
|
crop_brazil |
Logical. Crop global rasters to Brazil's bounding box
before extraction, significantly reducing memory use. Default |
use_cache |
Logical. If |
cache_dir |
Character. Root directory for all cached files.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
If municipalities is provided: a climasus_df tibble with
columns code_muni, date, and one column per pollutant (e.g.,
pm25_mean, o3_mean). Metadata: stage = "climate",
type = "pollution_ghap".
If municipalities = NULL: a named character vector of paths to
the cached NetCDF files.
Wei, J. et al. (2023). Estimating 1-km-resolution PM2.5 concentrations
across China using the space-time random forest approach.
Remote Sensing of Environment, 231, 111221.
DOI: doi:10.5281/zenodo.10800980
Wei, J. et al. GlobalHighAirPollutants (GHAP) v2. Zenodo. CC-BY 4.0.
PM2.5: doi:10.5281/zenodo.10800980 |
O3: doi:10.5281/zenodo.10208188 |
CO: doi:10.5281/zenodo.14207363
Spatial aggregation requires terra and exactextractr (both in
Suggests). The Parquet cache requires arrow (in Imports).
Install with install.packages(c("terra", "exactextractr")).
sus_climate_anomaly(), sus_climate_aggregate(),
sus_grid_era5(), sus_grid_pollution_cams(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # PM2.5 monthly for Mato Grosso, Jan-Mar 2020 ghap <- sus_grid_pollution_ghap( pollutants = "pm25", resolution = "monthly", years = 2020, months = 1:3, municipalities = mt_mun, lang = "pt" ) sus_meta(ghap, "stage") # "climate" sus_meta(ghap, "type") # "pollution_ghap" # O3 annual, all available years ghap_o3 <- sus_grid_pollution_ghap( pollutants = "o3", resolution = "annual", municipalities = mt_mun, lang = "en" ) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # PM2.5 monthly for Mato Grosso, Jan-Mar 2020 ghap <- sus_grid_pollution_ghap( pollutants = "pm25", resolution = "monthly", years = 2020, months = 1:3, municipalities = mt_mun, lang = "pt" ) sus_meta(ghap, "stage") # "climate" sus_meta(ghap, "type") # "pollution_ghap" # O3 annual, all available years ghap_o3 <- sus_grid_pollution_ghap( pollutants = "o3", resolution = "annual", municipalities = mt_mun, lang = "en" ) ## End(Not run)
sus_grid_pollution_merra2() downloads, spatially aggregates, and caches
NASA MERRA-2 aerosol and air quality data for Brazilian municipalities.
MERRA-2 (Modern-Era Retrospective Analysis for Research and Applications v2)
from NASA GMAO provides global atmospheric reanalysis from 1980 to
present at 0.6250.5 (~55 km). It is the longest
available reanalysis record for aerosol and pollution studies, making it
ideal for historical trend analysis and cross-validation with higher-
resolution products such as CAMS or GHAP.
Supported variables:
PM2.5 ("pm25") — derived from aerosol mass components
(): DUSMASS25 + SSSMASS25 + BCSMASS + 1.4*OCSMASS + SO4SMASS, each multiplied by 110^9 to convert kg/m
to .
AOD ("aod") — Total aerosol optical depth at 550 nm
(TOTEXTTAU), dimensionless, proxy for total aerosol column.
SO2 ("so2", experimental) — sulfate surface mass concentration
from M2I3NVAER ().
sus_grid_pollution_merra2( pollutants = c("pm25", "aod"), resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", earthdata_user = Sys.getenv("EARTHDATA_USER"), earthdata_pass = Sys.getenv("EARTHDATA_PASSWORD"), netrc_path = NULL, crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/merra2", lang = "pt", verbose = TRUE )sus_grid_pollution_merra2( pollutants = c("pm25", "aod"), resolution = "monthly", years = NULL, months = 1:12, municipalities = NULL, agg_fun = "mean", earthdata_user = Sys.getenv("EARTHDATA_USER"), earthdata_pass = Sys.getenv("EARTHDATA_PASSWORD"), netrc_path = NULL, crop_brazil = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/merra2", lang = "pt", verbose = TRUE )
pollutants |
Character vector. Variables to download.
Allowed: |
resolution |
Character. Temporal resolution of source files. One of:
|
years |
Integer vector. Years to download (1980 to current year).
|
months |
Integer vector (1–12). Months to include. Default |
municipalities |
An |
agg_fun |
Character. Spatial aggregation function for
|
earthdata_user |
Character. Earthdata username. Defaults to
|
earthdata_pass |
Character. Earthdata password. Defaults to
|
netrc_path |
Character. Path to a |
crop_brazil |
Logical. Crop rasters to Brazil's bounding box before
extraction to save memory. Default |
use_cache |
Logical. Reuse previously downloaded NetCDF files and
previously computed Parquet caches. Default |
cache_dir |
Character. Root cache directory.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
If municipalities is provided: a climasus_df with columns
code_muni, date, and one column per pollutant (e.g.,
pm25_merra2, aod_merra2). Metadata: stage = "climate",
type = "pollution_merra2".
If municipalities = NULL: a named character vector of paths to
cached NetCDF files.
A free NASA Earthdata Login account is required (https://urs.earthdata.nasa.gov). Set credentials in one of two ways:
Environment variables (recommended):
Sys.setenv(EARTHDATA_USER = "my_user",
EARTHDATA_PASSWORD = "my_pass")
.netrc file (for pipelines), then pass its path via
netrc_path:
machine urs.earthdata.nasa.gov login my_user password my_pass
After registering, activate GES DISC access at https://disc.gsfc.nasa.gov/earthdata-login.
Gelaro, R. et al. (2017). The Modern-Era Retrospective Analysis for
Research and Applications, Version 2 (MERRA-2).
Journal of Climate, 30(14), 5419–5454.
doi:10.1175/JCLI-D-16-0758.1
NASA/GSFC/EPS GMAO. MERRA-2 tavg1_2d_aer_Nx (M2T1NXAER v5.12.4).
NASA Goddard Earth Sciences DISC.
doi:10.5067/KLICLTZ8EM9D
sus_grid_pollution_cams(), sus_grid_pollution_ghap(),
sus_climate_anomaly(), sus_mod_dlnm()
## Not run: # Set credentials Sys.setenv(EARTHDATA_USER = "user", EARTHDATA_PASSWORD = "pass") library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Monthly PM2.5 + AOD, Q1 2020 merra2 <- sus_grid_pollution_merra2( pollutants = c("pm25", "aod"), resolution = "monthly", years = 2020, months = 1:3, municipalities = mt_mun, lang = "pt" ) sus_meta(merra2, "stage") # "climate" sus_meta(merra2, "type") # "pollution_merra2" # Historical PM2.5 trend 2000-2010, annual summary merra2_hist <- sus_grid_pollution_merra2( pollutants = "pm25", resolution = "monthly", years = 2000:2010, municipalities = mt_mun, lang = "en" ) ## End(Not run)## Not run: # Set credentials Sys.setenv(EARTHDATA_USER = "user", EARTHDATA_PASSWORD = "pass") library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Monthly PM2.5 + AOD, Q1 2020 merra2 <- sus_grid_pollution_merra2( pollutants = c("pm25", "aod"), resolution = "monthly", years = 2020, months = 1:3, municipalities = mt_mun, lang = "pt" ) sus_meta(merra2, "stage") # "climate" sus_meta(merra2, "type") # "pollution_merra2" # Historical PM2.5 trend 2000-2010, annual summary merra2_hist <- sus_grid_pollution_merra2( pollutants = "pm25", resolution = "monthly", years = 2000:2010, municipalities = mt_mun, lang = "en" ) ## End(Not run)
sus_grid_prodes() downloads INPE PRODES annual deforestation data from the
TerraBrasilis WFS API, spatially intersects deforestation polygons with
municipality boundaries, and returns municipality-level annual deforestation
areas as a climasus_df compatible with sus_mod_dlnm() and
sus_climate_anomaly().
PRODES (Projeto de Monitoramento do Desmatamento na Amazônia Legal por Satélite) is INPE's primary deforestation monitoring program. Deforestation exposure is a key driver of frontier malaria (SINAN), dengue, leishmaniasis, and respiratory disease from biomass burning in Brazil.
sus_grid_prodes( years, biomes = c("Amazon", "Cerrado", "MataAtlantica", "Caatinga", "Pampa", "Pantanal"), uf = NULL, municipalities = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/prodes", lang = "pt", verbose = TRUE )sus_grid_prodes( years, biomes = c("Amazon", "Cerrado", "MataAtlantica", "Caatinga", "Pampa", "Pantanal"), uf = NULL, municipalities = NULL, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/prodes", lang = "pt", verbose = TRUE )
years |
Integer vector. Years to download. Availability by biome: Amazon 2007–present; all others 2000–present. |
biomes |
Character vector. Biomes to include. Any combination of:
|
uf |
Character vector. Optional state filter (e.g., |
municipalities |
An |
use_cache |
Logical. Reuse previously downloaded GeoJSON files and
aggregated Parquet caches. Default |
cache_dir |
Character. Root cache directory.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress. Default |
If municipalities is provided: a climasus_df with columns
code_muni (character), date (Date, Jan 1 of the PRODES year),
year (integer), deforested_area_km2 (numeric, total area of
deforestation polygons intersecting the municipality), n_patches
(integer, count of distinct deforestation patches), and biome
(character). Metadata: stage = "climate", type = "prodes".
If municipalities = NULL: the raw deforestation polygon sf object
as a climasus_df with columns year, state, area_km, biome.
A PRODES year N covers August 1 of year N-1 through July 31 of year N.
The date column is set to YYYY-01-01 by convention (the publication
year). For time-series analyses, note that most deforestation peaks occur
during the dry season (July–October).
INPE PRODES via TerraBrasilis WFS. No authentication required.
All biomes accessed via https://terrabrasilis.dpi.inpe.br/geoserver/wfs
sf is required for spatial intersection when municipalities is provided.
httr2 and jsonlite are used for WFS downloads (in Suggests).
sus_grid_fires(), sus_climate_anomaly(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Annual deforestation for Mato Grosso municipalities, Amazon biome prodes <- sus_grid_prodes( years = 2015:2022, biomes = "Amazon", uf = "MT", municipalities = mt_mun, lang = "pt" ) sus_meta(prodes, "stage") # "climate" sus_meta(prodes, "type") # "prodes" # Raw polygon data (no aggregation) prodes_raw <- sus_grid_prodes( years = 2022, biomes = "Amazon", uf = "PA", lang = "en" ) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Annual deforestation for Mato Grosso municipalities, Amazon biome prodes <- sus_grid_prodes( years = 2015:2022, biomes = "Amazon", uf = "MT", municipalities = mt_mun, lang = "pt" ) sus_meta(prodes, "stage") # "climate" sus_meta(prodes, "type") # "prodes" # Raw polygon data (no aggregation) prodes_raw <- sus_grid_prodes( years = 2022, biomes = "Amazon", uf = "PA", lang = "en" ) ## End(Not run)
sus_grid_smvi() downloads the global flash drought inventory based on
the Soil Moisture Volatility Index (SMVI; Osman et al., 2024), spatially
assigns events to Brazilian municipalities, and returns annual or monthly
flash drought statistics as a climasus_df compatible with
sus_mod_dlnm() and sus_mod_vulnerability_index().
What is SMVI? SMVI detects flash droughts — rapid, high-impact soil moisture deficits that develop within days to weeks. Unlike SPI/SPEI/PDSI (which measure cumulative drought severity), SMVI captures the speed of soil moisture decline by comparing a 5-day running average of root-zone soil moisture (0–100 cm) against a 20-day running average. A flash drought event begins when the 5-day average drops below the 20-day average AND reaches the 20th percentile deficit threshold.
Why SMVI is different from SPI/SPEI/PDSI:
SPI/SPEI/PDSI measure how dry a period is (severity)
SMVI measures how fast a drought develops (onset speed) — flash droughts can devastate crops, trigger wildfires, and compromise water supply with little warning
Health connections in Brazil:
Malnutrition & food insecurity: flash droughts destroy crops within weeks; 1–3 month lag to increased child malnutrition in semi-arid Northeast and Amazônia
Leptospirosis: rapid soil rewetting after flash drought events concentrates rodents near water, increasing transmission; 1–4 week lag
Leishmaniasis: drought-driven human migration to water sources increases sandfly contact; 2-year lag documented in Bahia
Waterborne disease: water shortage during flash drought increases dependence on unclean sources
Data source: Global Flash Drought Inventory (Osman et al., 2024). Based on NASA GLDAS-2 root-zone soil moisture (1990–2021). No authentication required. Events file (109 MB) covers the full global domain at 0.25° resolution and is downloaded once and cached.
sus_grid_smvi( years = NULL, municipalities = NULL, aggregate_by = c("year", "month"), brazil_only = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/smvi", lang = "pt", verbose = TRUE )sus_grid_smvi( years = NULL, municipalities = NULL, aggregate_by = c("year", "month"), brazil_only = TRUE, use_cache = TRUE, cache_dir = "~/.climasus4r_cache/smvi", lang = "pt", verbose = TRUE )
years |
Integer vector. Years to include. Must be within 1990–2021.
|
municipalities |
An |
aggregate_by |
Character. Temporal resolution of the output when
|
brazil_only |
Logical. Filter the global dataset to Brazil's bounding
box (-75 to -28 lon, -35 to 6 lat) before processing. Default |
use_cache |
Logical. Reuse cached files. Default |
cache_dir |
Character. Root cache directory.
Default |
lang |
Character. Message language: |
verbose |
Logical. Print progress messages. Default |
If municipalities is provided: a climasus_df with columns:
code_muni — 7-digit IBGE municipality code
date — Date (Jan 1 for annual; first day of month for monthly)
n_fd_events — integer count of flash drought events
fd_total_days — total days under flash drought
fd_mean_severity — mean severity (SV) across events
fd_max_severity — maximum severity (SV) in the period
Metadata: stage = "climate", type = "smvi".
If municipalities = NULL: a climasus_df with raw event data
columns: cell_id, Lon, Lat, fstdate, lstdate, SV,
duration_days.
SMVI flash drought detection (Osman et al., 2024):
Compute 5-day and 20-day running averages of root-zone soil moisture (RZSM, 0–100 cm) from NASA GLDAS-2 data.
A flash drought onset occurs when the 5-day average drops below the 20-day average.
A flash drought event is confirmed when the RZSM deficit relative to the 20th percentile threshold is exceeded.
Severity (SV) quantifies the cumulative soil moisture deficit during the event.
Osman, M. et al. (2024). A global flash drought inventory based on soil
moisture volatility. Scientific Data, 11, 916.
doi:10.1038/s41597-024-03809-9
Data: https://www.hydroshare.org/resource/642ff72592404a17bb85a8a92b4dbcd6/
(CC BY-SA 4.0, no authentication required)
sus_climate_compute_spi(), sus_climate_compute_spei(),
sus_grid_pdsi(), sus_grid_join(), sus_mod_dlnm()
## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Annual flash drought statistics for Mato Grosso smvi_mt <- sus_grid_smvi( years = 2000:2021, municipalities = mt_mun, aggregate_by = "year", lang = "pt" ) sus_meta(smvi_mt, "stage") # "climate" sus_meta(smvi_mt, "type") # "smvi" # Monthly resolution smvi_mo <- sus_grid_smvi( years = 2015:2021, municipalities = mt_mun, aggregate_by = "month" ) # Join to health data for DLNM combined <- sus_grid_join(sih_mt, smvi_mt) ## End(Not run)## Not run: library(geobr) mt_mun <- read_municipality(code_muni = "MT", year = 2020) # Annual flash drought statistics for Mato Grosso smvi_mt <- sus_grid_smvi( years = 2000:2021, municipalities = mt_mun, aggregate_by = "year", lang = "pt" ) sus_meta(smvi_mt, "stage") # "climate" sus_meta(smvi_mt, "type") # "smvi" # Monthly resolution smvi_mo <- sus_grid_smvi( years = 2015:2021, municipalities = mt_mun, aggregate_by = "month" ) # Join to health data for DLNM combined <- sus_grid_join(sih_mt, smvi_mt) ## End(Not run)
Installs optional packages needed for specific feature groups. Tries multiple installation strategies, including Posit Package Manager (PPM) for pre-compiled binaries on Posit Cloud / Linux.
sus_install_deps(features = "all", force = FALSE, lang = "pt")sus_install_deps(features = "all", force = FALSE, lang = "pt")
features |
Character vector. Feature groups to install.
One or more of |
force |
Logical. Re-install even if the package is already available.
Default |
lang |
Character. Language for messages: |
"parquet"Installs arrow (fastest Parquet) and/or
nanoparquet (pure-R fallback, no C++ required).
"spatial"Installs sf, geobr, geocodebr, sfarrow,
censobr.
"plot"Installs ggplot2, plotly, patchwork, ggsci.
"models"Installs dlnm, mvmeta, survival, xgboost.
On Posit Cloud, PPM binaries are used automatically for faster installation.
## Not run: # Install all optional dependencies sus_install_deps() # Install only Parquet backend (no C++ required path) sus_install_deps("parquet") # Force reinstall arrow sus_install_deps("parquet", force = TRUE) ## End(Not run)## Not run: # Install all optional dependencies sus_install_deps() # Install only Parquet backend (no C++ required path) sus_install_deps("parquet") # Force reinstall arrow sus_install_deps("parquet", force = TRUE) ## End(Not run)
Unified interface for getting, setting, and managing metadata in
climasus_df objects, with native support for three storage backends:
in-memory tibble (default), columnar Parquet files via the
arrow package, and analytical DuckDB databases via the
duckdb package.
A single, unified interface for reading and writing metadata on
climasus_df objects (including Arrow Tables and DuckDB results).
Minimises namespace pollution by replacing the previous family of ten accessor functions.
sus_meta( x = NULL, field = NULL, system = NULL, stage = NULL, type = NULL, backend = NULL, add_history = NULL, print_history = FALSE, valid_values = NULL, ... ) sus_meta( x = NULL, field = NULL, system = NULL, stage = NULL, type = NULL, backend = NULL, add_history = NULL, print_history = FALSE, valid_values = NULL, ... )sus_meta( x = NULL, field = NULL, system = NULL, stage = NULL, type = NULL, backend = NULL, add_history = NULL, print_history = FALSE, valid_values = NULL, ... ) sus_meta( x = NULL, field = NULL, system = NULL, stage = NULL, type = NULL, backend = NULL, add_history = NULL, print_history = FALSE, valid_values = NULL, ... )
x |
A |
field |
Character. When provided as the only extra argument, returns
the value of that metadata field ( |
system |
Character. DATASUS system identifier (e.g. |
stage |
Character. Pipeline stage (e.g. |
type |
Character. Data type (e.g. |
backend |
Character. Storage backend: |
add_history |
Character. A single string appended (with timestamp) to the processing history. |
print_history |
Logical. If |
valid_values |
Character. When provided, returns the allowed values for
that vocabulary ( |
... |
Additional named metadata fields to update. |
Operation Dispatch Order:
valid_values — vocabulary query (no x required)
from_parquet — read Parquet file and reconstruct
from_duckdb — read DuckDB table and reconstruct
print_history — print processing history
add_history — append timestamped history entry
to_parquet — write to Parquet file
to_duckdb — register in DuckDB
field getter — return single metadata field
... updates — update metadata fields
Default — return all metadata as list
Metadata Persistence Across Backends:
When writing to Parquet, sus_meta is serialised as JSON and stored
in the Arrow schema metadata under the key "climasus_meta", making it
fully recoverable after reading the file back.
When writing to DuckDB, sus_meta is stored in a companion table named
<view_name>__meta within the same connection, enabling SQL-level
introspection of pipeline provenance.
Supports multiple backends:
climasus_df: metadata stored as sus_meta attribute
Arrow Table: metadata embedded in schema under "climasus_meta" key
DuckDB result: metadata extracted from companion <table>__meta table
Depends on the operation:
Get all metadata: Named list with all metadata fields.
Get specific field: Value of the requested field.
Update metadata: Updated climasus_df object.
Add history: Updated climasus_df with new history entry.
Print history: invisible(NULL) after printing.
Valid values: Character vector of allowed values.
to_parquet: Updated climasus_df (backend = "parquet").
from_parquet: Reconstructed climasus_df from file.
to_duckdb: Updated climasus_df (backend = "duckdb").
from_duckdb: Reconstructed climasus_df from DuckDB.
The updated climasus_df object, the requested field value, or
invisible(NULL) when print_history = TRUE.
The following named arguments trigger backend-specific operations when
passed via ...:
to_parquet = "<path>"Converts the climasus_df to an Arrow Table, embeds sus_meta
as JSON in the Parquet schema, and writes to <path>. Returns the
updated climasus_df with backend = "parquet".
from_parquet = "<path>"Reads a Parquet file written by to_parquet and reconstructs a
fully-featured climasus_df with all original metadata. Returns the
reconstructed object. x is ignored.
to_duckdb = <DBI connection>Registers the climasus_df as a DuckDB table (default name:
"climasus_data") and stores sus_meta in a companion table
<duckdb_view>__meta. Returns the updated climasus_df with
backend = "duckdb".
from_duckdb = <DBI connection>Reads a table from a DuckDB connection and reconstructs a
climasus_df. Combine with duckdb_view and
duckdb_query for fine-grained control.
duckdb_view = "<name>"Name of the DuckDB table/view to read or write (default:
"climasus_data").
duckdb_query = "<SQL>"Optional SQL WHERE clause or full SELECT statement applied
when reading from DuckDB.
write_parquet_climasus, write_duckdb_climasus
## Not run: # ── Basic metadata operations ────────────────────────────────────────────── # Get all metadata meta <- sus_meta(df) # Get specific field sus_meta(df, "stage") # "filter_cid" sus_meta(df, "backend") # "tibble" # Update metadata df <- sus_meta(df, stage = "clean", type = "clean") # Add to processing history df <- sus_meta(df, add_history = "Removed missing values") # Print history sus_meta(df, print_history = TRUE) # Query controlled vocabulary sus_meta(valid_values = "backend") # "tibble" "parquet" "duckdb" sus_meta(valid_values = "system") # "SIM" "SIH" ... # ── Arrow / Parquet backend ──────────────────────────────────────────────── # Write to Parquet (metadata embedded in schema) df <- sus_meta(df, to_parquet = "data/sim_respiratory.parquet") sus_meta(df, "backend") # "parquet" # Read back as climasus_df (metadata fully restored) df2 <- sus_meta(from_parquet = "data/sim_respiratory.parquet") sus_meta(df2, "stage") # "filter_cid" # ── DuckDB backend ───────────────────────────────────────────────────────── library(duckdb) con <- duckdb::dbConnect(duckdb::duckdb()) # Register as DuckDB view df <- sus_meta(df, to_duckdb = con, duckdb_view = "sim_respiratory") # SQL query directly on the view DBI::dbGetQuery(con, "SELECT sexo, COUNT(*) AS n FROM sim_respiratory GROUP BY sexo") # Read back as climasus_df (with optional SQL filter) df3 <- sus_meta(from_duckdb = con, duckdb_view = "sim_respiratory", duckdb_query = "WHERE ano_obito = 2020") sus_meta(df3, "stage") # "filter_cid" duckdb::dbDisconnect(con) ## End(Not run) ## Not run: # With climasus_df sus_meta(df) sus_meta(df, "stage") df <- sus_meta(df, stage = "filter_cid", type = "filter_cid") # With Arrow Table (auto-extracts from schema metadata) arrow_tbl <- as_arrow_climasus(df) sus_meta(arrow_tbl) # Extracts from Arrow schema sus_meta(arrow_tbl, "system") # With DuckDB result (if metadata table exists) con <- duckdb::dbConnect(duckdb::duckdb()) as_duckdb_climasus(df, con, "my_data") result <- DBI::dbGetQuery(con, "SELECT * FROM my_data") sus_meta(result) # Extracts from companion __meta table # Query valid values (no object needed) sus_meta(valid_values = "backend") ## End(Not run)## Not run: # ── Basic metadata operations ────────────────────────────────────────────── # Get all metadata meta <- sus_meta(df) # Get specific field sus_meta(df, "stage") # "filter_cid" sus_meta(df, "backend") # "tibble" # Update metadata df <- sus_meta(df, stage = "clean", type = "clean") # Add to processing history df <- sus_meta(df, add_history = "Removed missing values") # Print history sus_meta(df, print_history = TRUE) # Query controlled vocabulary sus_meta(valid_values = "backend") # "tibble" "parquet" "duckdb" sus_meta(valid_values = "system") # "SIM" "SIH" ... # ── Arrow / Parquet backend ──────────────────────────────────────────────── # Write to Parquet (metadata embedded in schema) df <- sus_meta(df, to_parquet = "data/sim_respiratory.parquet") sus_meta(df, "backend") # "parquet" # Read back as climasus_df (metadata fully restored) df2 <- sus_meta(from_parquet = "data/sim_respiratory.parquet") sus_meta(df2, "stage") # "filter_cid" # ── DuckDB backend ───────────────────────────────────────────────────────── library(duckdb) con <- duckdb::dbConnect(duckdb::duckdb()) # Register as DuckDB view df <- sus_meta(df, to_duckdb = con, duckdb_view = "sim_respiratory") # SQL query directly on the view DBI::dbGetQuery(con, "SELECT sexo, COUNT(*) AS n FROM sim_respiratory GROUP BY sexo") # Read back as climasus_df (with optional SQL filter) df3 <- sus_meta(from_duckdb = con, duckdb_view = "sim_respiratory", duckdb_query = "WHERE ano_obito = 2020") sus_meta(df3, "stage") # "filter_cid" duckdb::dbDisconnect(con) ## End(Not run) ## Not run: # With climasus_df sus_meta(df) sus_meta(df, "stage") df <- sus_meta(df, stage = "filter_cid", type = "filter_cid") # With Arrow Table (auto-extracts from schema metadata) arrow_tbl <- as_arrow_climasus(df) sus_meta(arrow_tbl) # Extracts from Arrow schema sus_meta(arrow_tbl, "system") # With DuckDB result (if metadata table exists) con <- duckdb::dbConnect(duckdb::duckdb()) as_duckdb_climasus(df, con, "my_data") result <- DBI::dbGetQuery(con, "SELECT * FROM my_data") sus_meta(result) # Extracts from companion __meta table # Query valid values (no object needed) sus_meta(valid_values = "backend") ## End(Not run)
Computes population attributable fractions (AF) and attributable numbers (AN)
from a climasus_dlnm object returned by sus_mod_dlnm(). Decomposes the
total burden into heat and cold components, reports AF at user-defined
exposure percentile ranges, and optionally breaks the burden down by month,
year, or season.
sus_mod_af( fit, threshold = NULL, range = NULL, pred_at = c(0.75, 0.9, 0.95, 0.99), by = NULL, nsim = 1000L, alpha = 0.05, lang = c("pt", "en", "es"), verbose = TRUE )sus_mod_af( fit, threshold = NULL, range = NULL, pred_at = c(0.75, 0.9, 0.95, 0.99), by = NULL, nsim = 1000L, alpha = 0.05, lang = c("pt", "en", "es"), verbose = TRUE )
fit |
A |
threshold |
Numeric or |
range |
Numeric vector |
pred_at |
Numeric vector (0-1). Quantiles defining the percentile-band
table. For each |
by |
Character or |
nsim |
Integer. Number of Monte Carlo simulations for CI. Default
|
alpha |
Numeric. Significance level for CI. Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_af object (named list) with:
$totalOne-row-per-component tibble (total/heat/cold) with AF, AN, and 95% CI.
$by_quantileAF/AN at each percentile band in pred_at.
$by_periodMonthly/yearly/seasonal point estimates; NULL when
by = NULL.
$dailyPer-day date + exposure + cases + AN + AF for mapping.
$customAF/AN for the custom range; NULL when not provided.
$metaNamed list of all parameters used.
Point estimates are obtained by calling dlnm::crosspred() at the observed
exposure values and computing for each
day. Confidence intervals use Monte Carlo simulation: nsim coefficient
vectors are drawn from via
MASS::mvrnorm, crosspred is re-evaluated for each draw, and AF quantiles
yield the CI. When MASS is unavailable the function falls back to
delta-method bounds from the original crosspred object.
Gasparrini, A., & Armstrong, B. (2013). The impact of heat waves on mortality. Epidemiology, 24(1), 64-71. doi:10.1097/EDE.0b013e3182770cb4
Gasparrini, A., et al. (2017). Attributable causes of heat-related mortality across 739 locations. The Lancet Planetary Health, 1(9), e360-e367. doi:10.1016/S2542-5196(17)30156-0
sus_mod_dlnm(), sus_mod_plot_dlnm()
## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos", lang = "pt") # Total burden with heat/cold split af <- sus_mod_af(fit, lang = "pt") print(af) tidy(af) # Monthly temporal breakdown af_m <- sus_mod_af(fit, by = "month", nsim = 200L, lang = "en") af_m$by_period # Pool across multiple cities dplyr::bind_rows(tidy(af_city1), tidy(af_city2)) ## End(Not run)## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos", lang = "pt") # Total burden with heat/cold split af <- sus_mod_af(fit, lang = "pt") print(af) tidy(af) # Monthly temporal breakdown af_m <- sus_mod_af(fit, by = "month", nsim = 200L, lang = "en") af_m$by_period # Pool across multiple cities dplyr::bind_rows(tidy(af_city1), tidy(af_city2)) ## End(Not run)
Aggregates city-level attributable fraction or excess mortality/morbidity
results into a ranked burden table showing each city's contribution to the
total population burden. Accepts climasus_af, climasus_excess, or
climasus_dlnm objects (DLNM fits are automatically converted to AF via
sus_mod_af()). Produces a concentration curve suitable for Lorenz-style
inequality analysis: how unevenly burden is distributed across cities.
sus_mod_burden( fits, component = "total", rank_by = NULL, top_n = NULL, nsim = 0L, alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_burden( fits, component = "total", rank_by = NULL, top_n = NULL, nsim = 0L, alpha = 0.05, lang = "pt", verbose = TRUE )
fits |
Named list of |
component |
Character. For |
rank_by |
Character or |
top_n |
Integer or |
nsim |
Integer. Monte Carlo simulations used when auto-computing AF
from |
alpha |
Numeric. Significance level for confidence intervals.
Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_burden object (named list) with:
$burden_tableTibble with one row per city (three rows per city
when component = "all"). For AF inputs: city, component,
n_cases, an, an_lo, an_hi, af_pct, af_pct_lo,
af_pct_hi, rank, pct_of_total. For excess inputs: city,
n_days, observed, expected, excess, excess_lo,
excess_hi, excess_pct, rank, pct_of_total.
$concentrationCity-level tibble with city, rank,
pct_of_total, and cumulative_pct for Lorenz-style concentration
analysis. Always one row per city, based on the total component.
$total_burdenNamed list with aggregate statistics: an_total
and af_pct_avg for AF inputs; excess_total and excess_pct_avg
for excess inputs. Also contains top_city and the top city's metric.
$metaNamed list of all parameters used in this call.
sus_mod_af(), sus_mod_excess(), sus_mod_pool(),
sus_mod_metaregression(), sus_mod_dlnm()
## Not run: # Rank cities by attributable number (AN) af_list <- list( fortaleza = sus_mod_af(fit_fortaleza, verbose = FALSE), recife = sus_mod_af(fit_recife, verbose = FALSE), salvador = sus_mod_af(fit_salvador, verbose = FALSE) ) burden <- sus_mod_burden(af_list, lang = "pt") print(burden) tidy(burden) # Show heat/cold split, keep top 5 cities sus_mod_burden(af_list, component = "all", top_n = 5L) # From DLNM fits directly (AF auto-computed via delta method) burden2 <- sus_mod_burden(dlnm_list, nsim = 0L, lang = "en") # Excess-based ranking exc_list <- list( sp = sus_mod_excess(fit_sp, method = "from_dlnm", verbose = FALSE), rj = sus_mod_excess(fit_rj, method = "from_dlnm", verbose = FALSE) ) sus_mod_burden(exc_list, rank_by = "excess_pct") ## End(Not run)## Not run: # Rank cities by attributable number (AN) af_list <- list( fortaleza = sus_mod_af(fit_fortaleza, verbose = FALSE), recife = sus_mod_af(fit_recife, verbose = FALSE), salvador = sus_mod_af(fit_salvador, verbose = FALSE) ) burden <- sus_mod_burden(af_list, lang = "pt") print(burden) tidy(burden) # Show heat/cold split, keep top 5 cities sus_mod_burden(af_list, component = "all", top_n = 5L) # From DLNM fits directly (AF auto-computed via delta method) burden2 <- sus_mod_burden(dlnm_list, nsim = 0L, lang = "en") # Excess-based ranking exc_list <- list( sp = sus_mod_excess(fit_sp, method = "from_dlnm", verbose = FALSE), rj = sus_mod_excess(fit_rj, method = "from_dlnm", verbose = FALSE) ) sus_mod_burden(exc_list, rank_by = "excess_pct") ## End(Not run)
Fits a time-stratified case-crossover model to quantify the association
between a climate exposure and a daily health outcome. Each time stratum
(month or week) acts as its own control, removing long-term trends and
seasonal confounding by design. Two fitting methods are supported:
"conditional_poisson" (GLM with stratum fixed effects, default) for
aggregate count data, and "clogit" (conditional logistic regression) for
binary outcomes or rare events.
sus_mod_casecrossover( data, outcome_col = "n_obitos", exposure_col, covariates = NULL, stratum = "month", lag = 0L, method = "conditional_poisson", family = "quasipoisson", alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_casecrossover( data, outcome_col = "n_obitos", exposure_col, covariates = NULL, stratum = "month", lag = 0L, method = "conditional_poisson", family = "quasipoisson", alpha = 0.05, lang = "pt", verbose = TRUE )
data |
A |
outcome_col |
Character. Name of the daily health outcome count column
(e.g., |
exposure_col |
Character. Name of the exposure column. Required; no
auto-detection is performed (unlike |
covariates |
Character vector or |
stratum |
Character. Time stratum type or name of an existing column:
|
lag |
Integer or integer vector. Lag(s) to apply to the exposure before
fitting. A single integer uses that specific lag; a vector uses the mean
of exposures at all specified lags. Default: |
method |
Character. Fitting method:
|
family |
Character. GLM family for |
alpha |
Numeric. Significance level for confidence intervals.
Default: |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_casecrossover list with:
$modelThe fitted model object: a glm for
"conditional_poisson" or a clogit object for "clogit".
$or_tableTibble with one row per exposure term:
term, lag_spec, estimate (log-OR), or, or_lo, or_hi,
p_value.
$dataThe analysis dataset after lag creation and NA removal:
columns date, outcome_val, exposure_val, stratum_id, and
any covariates.
$diagnosticsList: n_obs, n_cases, n_strata,
disp_ratio (for "conditional_poisson"), method, family.
$metaList of analysis parameters: outcome_col,
exposure_col, covariates, stratum, lag, method,
family, alpha, call_time.
"conditional_poisson" method (Whitaker et al., 2006):
where is a stratum-specific intercept (absorbed as
factor(stratum_id) in the GLM), is the (possibly lagged or
averaged) exposure on day , and are optional
time-varying covariates. The rate ratio is .
"clogit" method (Maclure, 1991; Levy et al., 2001):
Uses survival::clogit() with the binary indicator
as the outcome. Each case day is matched
to all other days within the same stratum as controls. This method is most
appropriate for rare events (low daily counts) and binary outcomes.
The lag argument controls how the daily exposure is lagged before the
association is estimated:
Single integer (e.g., lag = 0): uses the exposure exactly lag days
before the outcome day.
Integer vector (e.g., lag = 0:6): uses the arithmetic mean of
exposures at all specified lags — a moving average common for temperature
(e.g., lag = 0:6 is the "lag 0-6" or "mean temperature over 7 days").
Maclure, M. (1991). The case-crossover design: a method for studying transient effects on the risk of acute events. American Journal of Epidemiology, 133(2), 144-153. doi:10.1093/oxfordjournals.aje.a115853
Levy, D., Lumley, T., Sheppard, L., Kaufman, J., & Checkoway, H. (2001). Referent selection in case-crossover analyses of acute health effects of air pollution. Epidemiology, 12(2), 186-192.
Whitaker, H.J., Farrington, C.P., Spiessens, B., & Musonda, P. (2006). Tutorial in biostatistics: the self-controlled case series method. Statistics in Medicine, 25(10), 1768-1797. doi:10.1002/sim.2302
Armstrong, B.G., Gasparrini, A., & Tobias, A. (2014). Conditional Poisson models: a flexible alternative to conditional logistic case crossover analysis. BMC Medical Research Methodology, 14, 122. doi:10.1186/1471-2288-14-122
sus_mod_dlnm(), sus_mod_excess(), sus_mod_af()
## Not run: # Conditional Poisson with lag-0 temperature cc <- sus_mod_casecrossover( df_daily, outcome_col = "n_obitos", exposure_col = "tair_dry_bulb_c", stratum = "month", lag = 0L, lang = "pt" ) print(cc) tidy(cc) # Moving-average lag 0-6 cc_lag06 <- sus_mod_casecrossover( df_daily, outcome_col = "n_obitos", exposure_col = "tair_dry_bulb_c", lag = 0L:6L, lang = "en" ) ## End(Not run)## Not run: # Conditional Poisson with lag-0 temperature cc <- sus_mod_casecrossover( df_daily, outcome_col = "n_obitos", exposure_col = "tair_dry_bulb_c", stratum = "month", lag = 0L, lang = "pt" ) print(cc) tidy(cc) # Moving-average lag 0-6 cc_lag06 <- sus_mod_casecrossover( df_daily, outcome_col = "n_obitos", exposure_col = "tair_dry_bulb_c", lag = 0L:6L, lang = "en" ) ## End(Not run)
Fits a Distributed Lag Non-linear Model (DLNM) to quantify the association
between a climate exposure and a daily health outcome count. The function
accepts a climasus_df at stage "climate" / type "distributed_lag"
produced by sus_climate_aggregate(temporal_strategy = "distributed_lag"),
constructs the bidimensional crossbasis, fits a GLM, and returns a
climasus_dlnm object with the fitted model, pre-computed crosspred,
exposure-response and lag-response tables, and diagnostic statistics.
sus_mod_dlnm( df, outcome_col = "n_obitos", climate_col = NULL, lag_max = NULL, covariates = NULL, argvar = list(fun = "ns", df = 4), arglag = list(fun = "ns", df = 3), family = "quasipoisson", ns_df = NULL, dof_per_year = 4L, ref_value = NULL, pred_at = c(0.25, 0.5, 0.75, 0.9, 0.95, 0.99), alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_dlnm( df, outcome_col = "n_obitos", climate_col = NULL, lag_max = NULL, covariates = NULL, argvar = list(fun = "ns", df = 4), arglag = list(fun = "ns", df = 3), family = "quasipoisson", ns_df = NULL, dof_per_year = 4L, ref_value = NULL, pred_at = c(0.25, 0.5, 0.75, 0.9, 0.95, 0.99), alpha = 0.05, lang = "pt", verbose = TRUE )
df |
A |
outcome_col |
Character. Name of the daily health count column
(e.g., |
climate_col |
Character or |
lag_max |
Integer or |
covariates |
Character vector or |
argvar |
Named list. Arguments for the exposure dimension of the
|
arglag |
Named list. Arguments for the lag dimension of the
|
family |
Character. GLM family: |
ns_df |
Integer or |
dof_per_year |
Integer. Degrees of freedom per year of data used for
automatic |
ref_value |
Numeric or |
pred_at |
Numeric vector of quantile probabilities (0-1) at which to
report the cumulative exposure-response curve in |
alpha |
Numeric (0-1). Confidence level for intervals:
CI = |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress steps and warnings. Default |
A climasus_dlnm list with the following components:
$modelThe fitted glm object. Includes the crossbasis
in its model frame — compatible with dlnm::crosspred().
$crossbasisThe dlnm::crossbasis object encoding both
the exposure and lag dimensions.
$predA dlnm::crosspred object computed on a 100-point
grid from the 1st to 99th percentile of exposure. Contains
allRRfit, allRRlow, allRRhigh (cumulative overall effect)
and matRRfit, matRRlow, matRRhigh (lag-specific effects).
$exposure_responseTibble with cumulative RR at the
percentiles specified in pred_at: columns pct, exposure,
rr, lo, hi.
$lag_responseTibble with lag-specific RR at the 75th
percentile of exposure (for dlnm_lag plots): columns lag,
rr, lo, hi, rr_cum.
$modelsOne-row summary tibble for integration with
plot_climate_health(fit = ...): variable, n, family,
lag_max, ref_value, exposure_p75, rr, lo, hi,
lag_peak, disp_ratio, aic_poisson.
$data_dailyAggregated daily tibble used for model fitting (outcome summed; climate averaged across municipalities).
$diagnosticsList: disp_ratio, disp_category,
autocorr_pval, has_autocorr, aic_poisson, deviance,
null_deviance, df_residual.
$metaList of modelling parameters plus the input
sus_meta history for pipeline tracing.
The object also carries attr(result, "sus_meta") with an updated
history entry.
The DLNM models the log-linear association between an exposure history
and the daily count outcome
:
where is the cross-basis vector (outer product of the
exposure and lag basis matrices), and are natural splines
controlling seasonal confounding. The cumulative overall effect across
all lags at exposure level is:
where is the reference value (default: sample median).
"quasipoisson" (default, recommended): Robust to overdispersion
(). SE inflated by .
Recommended when disp_ratio > 1.5 (Armstrong, 2006).
"poisson": Valid only when . Provides
AIC/BIC but underestimates SE under overdispersion.
"negbin": Redirects to "quasipoisson" with a warning —
negative binomial is incompatible with dlnm::crossbasis().
argvar, arglag)
argvar |
When to use |
list(fun = "ns", df = 3) |
Mild non-linearity; conservative |
list(fun = "ns", df = 4) |
U/J shape (heat+cold, default) |
list(fun = "ns", df = 5) |
Complex dose-response; large N |
list(fun = "lin") |
Linear hypothesis test |
arglag |
When to use |
list(fun = "ns", df = 3) |
Smooth decay; temperature mortality |
list(fun = "ns", df = 4) |
Bimodal lag; cold effect |
list(fun = "poly", df = 2) |
Conservative; small samples |
ns_df, dof_per_year)A natural spline controls long-term
trends and seasonality that confound the climate-health association
(Bhaskaran et al., 2013). When ns_df = NULL the function auto-computes
. Recommended:
dof_per_year = 4: 1-2 year series; captures annual seasonality.
dof_per_year = 6: Subtropical Brazil; stronger seasonality.
dof_per_year = 8: Arboviral diseases; sub-seasonal variation.
ns_df = NULL with dof_per_year = 0: suppress time control
(use only when exposure is already an anomaly from climatology).
Gasparrini, A., Armstrong, B., & Kenward, M.G. (2010). Distributed lag non-linear models. Statistics in Medicine, 29(21), 2224-2234. doi:10.1002/sim.3940
Gasparrini, A. (2011). Distributed lag linear and non-linear models in R: the package dlnm. Journal of Statistical Software, 43(8), 1-20. doi:10.18637/jss.v043.i08
Gasparrini, A., Armstrong, B., & Kenward, M.G. (2014). Reducing and meta-analysing estimates from distributed lag non-linear models. BMC Medical Research Methodology, 14, 70. doi:10.1186/1471-2288-14-70
Armstrong, B. (2006). Models for the relationship between ambient temperature and daily mortality. Epidemiology, 17(6), 624-631.
Bhaskaran, K., Gasparrini, A., Hajat, S., Smeeth, L., & Armstrong, B. (2013). Time series regression studies in environmental epidemiology. International Journal of Epidemiology, 42(4), 1187-1195. doi:10.1093/ije/dyt092
Perkins, S.E. (2015). A review on the scientific understanding of heatwaves. Atmospheric Research, 164-165, 242-267.
sus_climate_aggregate(), sus_climate_compute_heatwaves()
## Not run: # Step 1: produce distributed_lag exposure data df_dl <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet_filled, climate_var = "tair_dry_bulb_c", temporal_strategy = "distributed_lag", lag_days = 21, lang = "pt" ) # Step 2: fit DLNM fit <- sus_mod_dlnm( df = df_dl, outcome_col = "n_obitos", lag_max = 21, argvar = list(fun = "ns", df = 4), arglag = list(fun = "ns", df = 3), family = "quasipoisson", dof_per_year = 4L, lang = "pt" ) print(fit) fit$exposure_response # RR cumulative at percentile grid fit$lag_response # RR by lag at p75 fit$diagnostics$disp_ratio # Step 3: visualise (requires plot_climate_health) # plots <- plot_climate_health( # data = df_dl, fit = fit, # plot_type = c("dlnm_surface", "dlnm_overall", "dlnm_lag") # ) ## End(Not run)## Not run: # Step 1: produce distributed_lag exposure data df_dl <- sus_climate_aggregate( health_data = sf_sim_spatial, climate_data = df_inmet_filled, climate_var = "tair_dry_bulb_c", temporal_strategy = "distributed_lag", lag_days = 21, lang = "pt" ) # Step 2: fit DLNM fit <- sus_mod_dlnm( df = df_dl, outcome_col = "n_obitos", lag_max = 21, argvar = list(fun = "ns", df = 4), arglag = list(fun = "ns", df = 3), family = "quasipoisson", dof_per_year = 4L, lang = "pt" ) print(fit) fit$exposure_response # RR cumulative at percentile grid fit$lag_response # RR by lag at p75 fit$diagnostics$disp_ratio # Step 3: visualise (requires plot_climate_health) # plots <- plot_climate_health( # data = df_dl, fit = fit, # plot_type = c("dlnm_surface", "dlnm_overall", "dlnm_lag") # ) ## End(Not run)
Estimates excess counts (observed minus expected baseline) for daily health
outcome series in the context of climate-health research. Supports three
baseline methods: counterfactual extraction from a fitted DLNM
("from_dlnm"), quasi-Poisson GLM with natural splines ("spline"), and
Serfling sinusoidal regression ("serfling"). Confidence intervals are
derived from the baseline model's prediction standard errors. A z-score
flag identifies statistically significant excess events.
sus_mod_excess( data, outcome_col = NULL, date_col = "date", control_period = NULL, study_period = NULL, method = NULL, dof_per_year = 8L, harmonics = 2L, family = "quasipoisson", threshold_z = 1.96, by = NULL, alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_excess( data, outcome_col = NULL, date_col = "date", control_period = NULL, study_period = NULL, method = NULL, dof_per_year = 8L, harmonics = 2L, family = "quasipoisson", threshold_z = 1.96, by = NULL, alpha = 0.05, lang = "pt", verbose = TRUE )
data |
A |
outcome_col |
Character. Name of the outcome count column. Required
when |
date_col |
Character. Name of the date column. Default |
control_period |
Date vector of length 2 specifying the reference
period used to fit the baseline model, e.g.
|
study_period |
Date vector of length 2 specifying the period for which
excess is reported. Default |
method |
Character. Baseline estimation method:
|
dof_per_year |
Integer. Degrees of freedom per year for the spline
baseline. Default |
harmonics |
Integer. Number of sinusoidal harmonics in the Serfling
model. Default |
family |
Character. GLM family: |
threshold_z |
Numeric. Z-score threshold for flagging excess events.
Default |
by |
Character or |
alpha |
Numeric. Significance level for confidence intervals.
Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_excess list with:
$dailyTibble with one row per day: date, observed,
expected, expected_lo, expected_hi, excess, excess_lo,
excess_hi, z_score, is_excess.
$totalOne-row tibble: total observed, expected, excess, excess percentage, and their confidence bounds.
$by_periodTemporal breakdown tibble (when by is not NULL).
$modelThe fitted baseline GLM object (NULL for
method = "from_dlnm").
$metaMetadata list: method, outcome_col, date_col,
control_period, study_period, family, dof_per_year,
harmonics, threshold_z, n_obs, call_time.
"spline" and "serfling" methods: A quasi-Poisson GLM is fitted on
the control_period:
where is either a natural spline over calendar date ("spline")
or a Serfling harmonic:
("serfling"). Expected counts for the study period are predicted from
this model.
"from_dlnm" method: Given a climasus_dlnm object, the counterfactual
expected mortality without the climate-exposure effect is:
where are fitted values and is the
cumulative relative risk at the observed exposure from
dlnm::crosspred(). This yields the Gasparrini & Armstrong (2013)
temperature-attributable excess.
sus_mod_dlnm(), sus_mod_af(), sus_mod_plot_dlnm()
## Not run: # From a fitted DLNM exc <- sus_mod_excess(fit_dlnm, method = "from_dlnm", lang = "en") # Standalone spline baseline for a heat wave period exc <- sus_mod_excess( df_daily, outcome_col = "n_obitos", control_period = c(as.Date("2018-01-01"), as.Date("2021-12-31")), study_period = c(as.Date("2022-01-01"), as.Date("2022-12-31")), method = "spline", lang = "pt" ) print(exc) tidy(exc) ## End(Not run)## Not run: # From a fitted DLNM exc <- sus_mod_excess(fit_dlnm, method = "from_dlnm", lang = "en") # Standalone spline baseline for a heat wave period exc <- sus_mod_excess( df_daily, outcome_col = "n_obitos", control_period = c(as.Date("2018-01-01"), as.Date("2021-12-31")), study_period = c(as.Date("2022-01-01"), as.Date("2022-12-31")), method = "spline", lang = "pt" ) print(exc) tidy(exc) ## End(Not run)
Fits a segmented quasi-Poisson regression to estimate the immediate and sustained effects of one or more interruptions (policies, extreme events, pandemics) on a daily health outcome count series. The model decomposes each interruption into a level change (immediate step) and a slope change (sustained trend shift), controlling for the underlying time trend and seasonal variation via harmonic terms. A counterfactual projection shows what would have been expected had the interruption not occurred.
sus_mod_its( data, outcome_col = "n_obitos", date_col = "date", interruption_dates, harmonics = 2L, family = "quasipoisson", covariates = NULL, alpha = 0.05, counterfactual = TRUE, lang = "pt", verbose = TRUE )sus_mod_its( data, outcome_col = "n_obitos", date_col = "date", interruption_dates, harmonics = 2L, family = "quasipoisson", covariates = NULL, alpha = 0.05, counterfactual = TRUE, lang = "pt", verbose = TRUE )
data |
A |
outcome_col |
Character. Name of the daily health outcome count column.
Default: |
date_col |
Character. Name of the date column. Default: |
interruption_dates |
Date or character vector of at least one
interruption date (ISO |
harmonics |
Integer. Number of sinusoidal harmonic pairs for seasonal
control ( |
family |
Character. GLM family: |
covariates |
Character vector or |
alpha |
Numeric. Significance level for confidence intervals.
Default: |
counterfactual |
Logical. Compute and return counterfactual predictions.
Default: |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_its list with:
$modelThe fitted glm object.
$effectsTibble with one row per interruption: label,
interruption_date, level_ratio, level_ci_lo, level_ci_hi,
level_p, slope_daily_log, slope_ratio_annual, slope_p.
$counterfactualTibble with daily date, observed,
predicted (fitted values), counterfactual, cf_lo, cf_hi,
ratio_to_cf, prevented. NULL when counterfactual = FALSE.
$segmentsTibble with one row per segment (pre-interruption and
each post-interruption interval): segment, start_date, end_date,
n_days, mean_observed, mean_predicted, mean_counterfactual.
$dataThe analysis dataset with all model covariates.
$metaAnalysis parameters and diagnostics.
For interruption dates , the
segmented Poisson GLM is:
where is the step indicator and
is the slope-change ("hockey stick")
basis. The immediate rate ratio at interruption is
; the sustained trend shift is
per day (or per year).
The counterfactual is the model prediction with all and
set to zero — i.e., the pre-interruption baseline trend projected forward
through the study period. The difference observed - counterfactual is the
estimated total attributable change.
Bernal, J.L., Cummins, S., & Gasparrini, A. (2017). Interrupted time series regression for the evaluation of public health interventions: a tutorial. International Journal of Epidemiology, 46(1), 348-355. doi:10.1093/ije/dyw098
Penfold, R.B., & Zhang, F. (2013). Use of interrupted time series analysis in evaluating health care quality improvements. Academic Pediatrics, 13(6 Suppl), S38-44. doi:10.1016/j.acap.2013.08.002
sus_mod_excess(), sus_mod_casecrossover(), sus_mod_dlnm()
## Not run: # Single interruption (COVID-19 pandemic onset) its <- sus_mod_its( df_daily, outcome_col = "n_obitos", interruption_dates = "2020-03-17", harmonics = 2L, lang = "pt" ) print(its) tidy(its) # Multiple interruptions its2 <- sus_mod_its( df_daily, outcome_col = "n_obitos", interruption_dates = c("2020-03-17", "2021-01-18"), lang = "en" ) ## End(Not run)## Not run: # Single interruption (COVID-19 pandemic onset) its <- sus_mod_its( df_daily, outcome_col = "n_obitos", interruption_dates = "2020-03-17", harmonics = 2L, lang = "pt" ) print(its) tidy(its) # Multiple interruptions its2 <- sus_mod_its( df_daily, outcome_col = "n_obitos", interruption_dates = c("2020-03-17", "2021-01-18"), lang = "en" ) ## End(Not run)
Extends two-stage multivariate meta-analysis (sus_mod_pool()) by including
city-level covariates (e.g., mean temperature, poverty index, age structure)
to explain between-city heterogeneity in climate-health associations.
Covariates are automatically standardized to mean 0, SD 1 so the intercept
represents the predicted association for an "average city". Returns
covariate Wald tests, residual heterogeneity statistics, and BLUP
predictions per city adjusted for covariate information.
sus_mod_metaregression( fits, covariates, covariate_cols = NULL, city_col = NULL, pred_at = c(0.75, 0.9, 0.95, 0.99), blup = TRUE, method = "reml", alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_metaregression( fits, covariates, covariate_cols = NULL, city_col = NULL, pred_at = c(0.75, 0.9, 0.95, 0.99), blup = TRUE, method = "reml", alpha = 0.05, lang = "pt", verbose = TRUE )
fits |
A named list of |
covariates |
A |
covariate_cols |
Character vector of column names to use as
meta-regression predictors. Default |
city_col |
Character. Name of the column in |
pred_at |
Numeric vector of quantile probabilities (0–1) for the
exposure-response summary table. Default |
blup |
Logical. Compute BLUP city-specific predictions? Default |
method |
Character. |
alpha |
Numeric. Significance level for confidence intervals.
Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_metaregression list with:
$mvmeta_fitThe mvmeta model with covariates.
$null_fitIntercept-only mvmeta model (for heterogeneity
comparison).
$pooled_preddlnm::crosspred for the average city (all
standardized covariates = 0, i.e., the intercept).
$blup_predsNamed list of per-city BLUP crosspred objects
(when blup = TRUE).
$city_tableTibble: one row per city with raw and BLUP RRs at the 75th percentile exposure.
$covariate_testsTibble: one row per covariate with Wald
chi-square statistic (df = n_crossbasis_coef) and p-value.
$heterogeneityTibble comparing null and full-model heterogeneity: Cochran Q, df, p-value, I^2, and proportion of heterogeneity explained by covariates (R^2_het).
$cov_scalesTibble with the mean and SD used to standardize each covariate (for back-transformation).
$metaMetadata: climate_col, outcome_col, lag_max,
n_cities, city_names, covariate_cols, method, alpha,
call_time.
Let be the -dimensional vector of
cross-basis coefficients for city , with variance-covariance
matrix . The meta-regression model is:
where is the -vector of regression
coefficients for covariate and is the residual
between-city covariance estimated by REML. Because covariates are
standardized before fitting, is the predicted
association for a city with mean covariate values.
The significance of each covariate is assessed by a multivariate Wald test:
where is the estimated covariance of
.
Gasparrini, A., et al. (2012). Multivariate meta-analysis for non-linear and other multi-parameter associations. Statistics in Medicine, 31(29), 3821-3839. doi:10.1002/sim.5471
Berkey, C.S., et al. (1998). Meta-analysis of multiple outcomes by regression with random effects. Statistics in Medicine, 17(22), 2537-2550.
sus_mod_pool(), sus_mod_dlnm(), sus_mod_sensitivity()
## Not run: # City-level covariates: mean annual temperature and poverty index city_meta <- data.frame( mean_temp = c(28.5, 22.1, 19.8), poverty_pct = c(42, 28, 15), row.names = c("fortaleza", "belo_horizonte", "curitiba") ) mr <- sus_mod_metaregression(fits, city_meta, lang = "en") print(mr) tidy(mr) ## End(Not run)## Not run: # City-level covariates: mean annual temperature and poverty index city_meta <- data.frame( mean_temp = c(28.5, 22.1, 19.8), poverty_pct = c(42, 28, 15), row.names = c("fortaleza", "belo_horizonte", "curitiba") ) mr <- sus_mod_metaregression(fits, city_meta, lang = "en") print(mr) tidy(mr) ## End(Not run)
Trains an XGBoost gradient-boosted tree model to predict health outcomes
(disease counts, mortality, hospitalizations) from climate and socioeconomic
features. Accepts any aggregated data frame produced by the climasus4r
pipeline (or a plain data.frame). Uses k-fold cross-validation to select
the optimal number of trees (nrounds) and returns out-of-fold (OOF)
predictions alongside the final model trained on full data.
sus_mod_ml( df, outcome_col, feature_cols = NULL, id_col = NULL, objective = "count:poisson", nrounds = 500L, max_depth = 6L, eta = 0.05, subsample = 0.8, colsample_bytree = 0.8, min_child_weight = 1, nfold = 5L, early_stopping = 50L, seed = 42L, lang = "pt", verbose = TRUE )sus_mod_ml( df, outcome_col, feature_cols = NULL, id_col = NULL, objective = "count:poisson", nrounds = 500L, max_depth = 6L, eta = 0.05, subsample = 0.8, colsample_bytree = 0.8, min_child_weight = 1, nfold = 5L, early_stopping = 50L, seed = 42L, lang = "pt", verbose = TRUE )
df |
A data frame (plain or |
outcome_col |
Character. Name of the column to predict (the target variable). Must be numeric. |
feature_cols |
Character vector or |
id_col |
Character or |
objective |
Character. XGBoost objective function. One of
|
nrounds |
Integer. Maximum number of boosting rounds. The optimal
value is selected via early stopping during cross-validation. Default
|
max_depth |
Integer. Maximum tree depth. Default |
eta |
Numeric. Learning rate (step size shrinkage). Default |
subsample |
Numeric ∈ (0, 1]. Row subsampling ratio per tree.
Default |
colsample_bytree |
Numeric ∈ (0, 1]. Column subsampling ratio per
tree. Default |
min_child_weight |
Numeric. Minimum sum of instance weight in a leaf.
Default |
nfold |
Integer. Number of cross-validation folds. Default |
early_stopping |
Integer. Stop training if the CV metric does not
improve for this many consecutive rounds. Default |
seed |
Integer. Random seed for reproducibility. Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
This function complements the DLNM epidemiological pipeline
(sus_mod_dlnm()): DLNM models the exposure-response relationship and
provides causal inference; sus_mod_ml() focuses on predictive accuracy
across a wider feature space and can incorporate lagged climate variables,
socioeconomic covariates, and spatial predictors simultaneously.
A climasus_ml object (named list) with:
$predictionsTibble with one row per (non-NA) observation:
observed, fitted (train-set prediction), cv_predicted
(out-of-fold CV prediction), residual (observed - cv_predicted),
and the id_col and outcome_col columns if present.
$importanceTibble sorted by Gain (descending): Feature,
Gain (average loss reduction per split), Cover (average number
of samples per split), Frequency (proportion of splits using this
feature). These are the standard XGBoost importance metrics.
$performanceNamed list: RMSE_train, MAE_train,
R2_train, RMSE_cv, MAE_cv, R2_cv, Pearson_cv
(correlation between observed and OOF predictions), and
best_nrounds.
$modelThe final XGBoost model (class xgb.Booster) trained
on the full dataset using best_nrounds. Pass to predict() to
generate forecasts for new data (see predict.climasus_ml()).
$cv_logData frame from xgb.cv() with per-round train and
test metrics. Useful for plotting the learning curve.
$metaNamed list of all parameters used in this call.
The objective controls the loss function and the scale of predictions:
"count:poisson"Poisson log-linear model for non-negative integer counts (deaths, hospitalizations). Predictions are in count scale (predicted lambda). Default — appropriate for most DATASUS outcomes.
"reg:squarederror"Squared-error regression for continuous outcomes (rates, indices). Predictions are in the same scale as the outcome.
"binary:logistic"Binary outcome (0/1). Predictions are probabilities ∈ (0, 1).
sus_mod_dlnm(), sus_mod_vulnerability_index(),
sus_climate_aggregate(), predict.climasus_ml()
## Not run: # From a climasus4r pipeline output (aggregated city x day data with # climate columns from sus_climate_aggregate()) ml <- sus_mod_ml( df = df_aggregated, outcome_col = "n_obitos", id_col = "name_muni", # group-aware CV by city objective = "count:poisson", nfold = 5L, lang = "pt" ) print(ml) tidy(ml) # predictions tibble # Forecast for a new climate scenario new_climate <- data.frame(tair_max_c = 36, rh_pct_mean = 60, ...) predict(ml, newdata = new_climate) ## End(Not run)## Not run: # From a climasus4r pipeline output (aggregated city x day data with # climate columns from sus_climate_aggregate()) ml <- sus_mod_ml( df = df_aggregated, outcome_col = "n_obitos", id_col = "name_muni", # group-aware CV by city objective = "count:poisson", nfold = 5L, lang = "pt" ) print(ml) tidy(ml) # predictions tibble # Forecast for a new climate scenario new_climate <- data.frame(tair_max_c = 36, rh_pct_mean = 60, ...) predict(ml, newdata = new_climate) ## End(Not run)
Produces bar charts, forest plots, and quantile summaries from a
climasus_af object returned by sus_mod_af(). All visualisation types
follow standard environmental epidemiology burden-of-disease reporting.
sus_mod_plot_af( fit, type = c("bar", "forest", "quantile"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_af( fit, type = c("bar", "forest", "quantile"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
fit |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"bar" |
Grouped bar chart of AF% with CI by component (heat/cold/total) |
"forest" |
Horizontal forest plot of AN +/- CI by component |
"quantile" |
Bar chart of AF% across exposure quantile bands (requires $by_quantile)
|
sus_mod_af(), sus_mod_plot_dlnm()
## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos") af <- sus_mod_af(fit) sus_mod_plot_af(af, type = "bar", lang = "pt") sus_mod_plot_af(af, type = "forest", lang = "en") sus_mod_plot_af(af, type = "quantile", lang = "es") out <- sus_mod_plot_af(af, output_type = "all") out$table ## End(Not run)## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos") af <- sus_mod_af(fit) sus_mod_plot_af(af, type = "bar", lang = "pt") sus_mod_plot_af(af, type = "forest", lang = "en") sus_mod_plot_af(af, type = "quantile", lang = "es") out <- sus_mod_plot_af(af, output_type = "all") out$table ## End(Not run)
Produces lollipop charts, Lorenz concentration curves, and stacked bar
charts from a climasus_burden object returned by sus_mod_burden().
sus_mod_plot_burden( x, type = c("lollipop", "lorenz", "stacked"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_burden( x, type = c("lollipop", "lorenz", "stacked"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"lollipop" |
Ranked lollipop chart of city AN or excess burden (default) |
"lorenz" |
Lorenz concentration curve showing burden inequality across cities |
"stacked" |
Stacked heat/cold bar by city (only for AF input with component = "all")
|
sus_mod_burden(), sus_mod_af(), sus_mod_excess()
## Not run: burden <- sus_mod_burden(af_list, lang = "pt") sus_mod_plot_burden(burden, type = "lollipop", lang = "pt") sus_mod_plot_burden(burden, type = "lorenz", lang = "en") sus_mod_plot_burden(burden, type = "stacked", lang = "es") out <- sus_mod_plot_burden(burden, output_type = "all") out$table ## End(Not run)## Not run: burden <- sus_mod_burden(af_list, lang = "pt") sus_mod_plot_burden(burden, type = "lollipop", lang = "pt") sus_mod_plot_burden(burden, type = "lorenz", lang = "en") sus_mod_plot_burden(burden, type = "stacked", lang = "es") out <- sus_mod_plot_burden(burden, output_type = "all") out$table ## End(Not run)
Produces publication-quality visualisations and statistical summary tables
from a climasus_dlnm object returned by sus_mod_dlnm(). Implements all
visualisation types standard in distributed lag non-linear model (DLNM)
epidemiology: overall exposure-response, lag-response, bidimensional surface,
contour map, lag-stratified slices, exposure distribution, and time series.
sus_mod_plot_dlnm( fit, type = c("overall", "lag", "surface", "contour", "slice", "distribution", "series"), output_type = c("plot", "table", "all"), exposure_at = NULL, lags_at = c(0L, 3L, 7L, 14L, 21L), pred_at = c(0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99), interactive = FALSE, color_palette = "npg", base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_dlnm( fit, type = c("overall", "lag", "surface", "contour", "slice", "distribution", "series"), output_type = c("plot", "table", "all"), exposure_at = NULL, lags_at = c(0L, 3L, 7L, 14L, 21L), pred_at = c(0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99), interactive = FALSE, color_palette = "npg", base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
fit |
A |
type |
Character. Plot type (see Plot types section). Default
|
output_type |
Character. What to return: |
exposure_at |
Numeric or |
lags_at |
Integer vector. Lag times shown in the |
pred_at |
Numeric vector (0–1). Quantile probabilities at which to
report cumulative RR in the statistical table. Default:
|
interactive |
Logical. |
color_palette |
Character. Name of a ggsci palette. Default
|
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" → a ggplot or plotly object.
"table" → a gt_tbl (or tibble when gt is unavailable).
"all" → a named list: $plot, $table, $data.
type)
type |
Description | Key reference |
"overall" |
Cumulative exposure-response curve with CI + exposure histogram | Gasparrini et al. (2010) |
"lag" |
Lag-specific and cumulative lag-response at a given exposure | Gasparrini et al. (2010) |
"surface" |
3-D bidimensional exposure × lag response surface | Gasparrini (2011) |
"contour" |
2-D contour heat map of exposure × lag (publication-friendly) | Gasparrini et al. (2014) |
"slice" |
Exposure-response curves at specific lag times (multilag) | Armstrong (2006) |
"distribution" |
Exposure variable histogram/density with quartile markers | Bhaskaran et al. (2013) |
"series" |
Daily outcome count + exposure time series | Bhaskaran et al. (2013) |
output_type = "table" or "all")When a table is requested, returns a gt object (or tibble fallback) with four sections: (1) model specification, (2) cumulative RR at exposure percentiles, (3) lag peak summary, and (4) model diagnostics following reporting standards in Gasparrini et al. (2014) and Bhaskaran et al. (2013).
Gasparrini, A., Armstrong, B., & Kenward, M.G. (2010). Distributed lag non-linear models. Statistics in Medicine, 29(21), 2224–2234. doi:10.1002/sim.3940
Gasparrini, A. (2011). Distributed lag linear and non-linear models in R: the package dlnm. Journal of Statistical Software, 43(8), 1–20. doi:10.18637/jss.v043.i08
Gasparrini, A., Armstrong, B., & Kenward, M.G. (2014). Reducing and meta-analysing estimates from distributed lag non-linear models. BMC Medical Research Methodology, 14, 70. doi:10.1186/1471-2288-14-70
Armstrong, B. (2006). Models for the relationship between ambient temperature and daily mortality. Epidemiology, 17(6), 624–631.
Bhaskaran, K., Gasparrini, A., Hajat, S., Smeeth, L., & Armstrong, B. (2013). Time series regression studies in environmental epidemiology. International Journal of Epidemiology, 42(4), 1187–1195. doi:10.1093/ije/dyt092
sus_mod_dlnm(), sus_climate_plot_heatwaves()
## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos", lang = "pt") # Overall exposure-response curve (static) sus_mod_plot_dlnm(fit, type = "overall", lang = "pt") # Interactive lag-response sus_mod_plot_dlnm(fit, type = "lag", interactive = TRUE, lang = "en") # 3-D surface (interactive only) sus_mod_plot_dlnm(fit, type = "surface", interactive = TRUE) # Full output with table out <- sus_mod_plot_dlnm(fit, type = "overall", output_type = "all", lang = "pt") out$plot out$table ## End(Not run)## Not run: fit <- sus_mod_dlnm(df_dl, outcome_col = "n_obitos", lang = "pt") # Overall exposure-response curve (static) sus_mod_plot_dlnm(fit, type = "overall", lang = "pt") # Interactive lag-response sus_mod_plot_dlnm(fit, type = "lag", interactive = TRUE, lang = "en") # 3-D surface (interactive only) sus_mod_plot_dlnm(fit, type = "surface", interactive = TRUE) # Full output with table out <- sus_mod_plot_dlnm(fit, type = "overall", output_type = "all", lang = "pt") out$plot out$table ## End(Not run)
Produces feature importance charts, observed-vs-predicted scatter plots,
and cross-validation loss curves from a climasus_ml object returned by
sus_mod_ml().
sus_mod_plot_ml( x, type = c("importance", "fit", "cv_log"), output_type = c("plot", "table", "all"), n_top = 20L, interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_ml( x, type = c("importance", "fit", "cv_log"), output_type = c("plot", "table", "all"), n_top = 20L, interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
n_top |
Integer. Maximum number of features to show in the importance
plot. Default |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"importance" |
Horizontal bar chart of XGBoost feature Gain (top n_top features) |
"fit" |
Observed vs. out-of-fold CV-predicted scatter with R² and RMSE annotation |
"cv_log" |
Train/test loss per boosting round from xgb.cv(), with best-round marker
|
sus_mod_ml(), sus_mod_plot_dlnm()
## Not run: ml <- sus_mod_ml(df, outcome_col = "n_obitos", feature_cols = c("tmax", "pop")) sus_mod_plot_ml(ml, type = "importance", lang = "pt") sus_mod_plot_ml(ml, type = "fit", lang = "en") sus_mod_plot_ml(ml, type = "cv_log", lang = "es") out <- sus_mod_plot_ml(ml, output_type = "all") out$table ## End(Not run)## Not run: ml <- sus_mod_ml(df, outcome_col = "n_obitos", feature_cols = c("tmax", "pop")) sus_mod_plot_ml(ml, type = "importance", lang = "pt") sus_mod_plot_ml(ml, type = "fit", lang = "en") sus_mod_plot_ml(ml, type = "cv_log", lang = "es") out <- sus_mod_plot_ml(ml, output_type = "all") out$table ## End(Not run)
Produces exposure-response curves, city-specific forest plots, and BLUP
spaghetti plots from a climasus_pool object returned by sus_mod_pool().
sus_mod_plot_pool( x, type = c("overall", "forest", "spaghetti"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_pool( x, type = c("overall", "forest", "spaghetti"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"overall" |
Pooled exposure-response curve with CI ribbon |
"forest" |
City-specific RR at exposure p75 with CI (original and BLUP) |
"spaghetti" |
Per-city BLUP curves overlaid on the pooled curve |
sus_mod_pool(), sus_mod_plot_dlnm()
## Not run: pool <- sus_mod_pool(fits, lang = "pt") sus_mod_plot_pool(pool, type = "overall", lang = "pt") sus_mod_plot_pool(pool, type = "forest", lang = "en") sus_mod_plot_pool(pool, type = "spaghetti", lang = "en") out <- sus_mod_plot_pool(pool, output_type = "all") out$table ## End(Not run)## Not run: pool <- sus_mod_pool(fits, lang = "pt") sus_mod_plot_pool(pool, type = "overall", lang = "pt") sus_mod_plot_pool(pool, type = "forest", lang = "en") sus_mod_plot_pool(pool, type = "spaghetti", lang = "en") out <- sus_mod_plot_pool(pool, output_type = "all") out$table ## End(Not run)
Produces exposure-response curve overlays, hot-vs-cold RR scatter plots,
and grouped forest plots from a climasus_sensitivity object returned by
sus_mod_sensitivity().
sus_mod_plot_sensitivity( x, type = c("curves", "scatter", "bar"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_sensitivity( x, type = c("curves", "scatter", "bar"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"curves" |
Overlay of each stratum's exposure-response curve with CI ribbon |
"scatter" |
Hot RR vs Cold RR per stratum; point size encodes sensitivity index |
"bar" |
Horizontal forest plot of hot and cold RR per stratum ordered by SI |
sus_mod_sensitivity(), sus_mod_plot_dlnm()
## Not run: sens <- sus_mod_sensitivity(fits, lang = "pt") sus_mod_plot_sensitivity(sens, type = "curves", lang = "pt") sus_mod_plot_sensitivity(sens, type = "scatter", lang = "en") sus_mod_plot_sensitivity(sens, type = "bar", lang = "es") out <- sus_mod_plot_sensitivity(sens, output_type = "all") out$table ## End(Not run)## Not run: sens <- sus_mod_sensitivity(fits, lang = "pt") sus_mod_plot_sensitivity(sens, type = "curves", lang = "pt") sus_mod_plot_sensitivity(sens, type = "scatter", lang = "en") sus_mod_plot_sensitivity(sens, type = "bar", lang = "es") out <- sus_mod_plot_sensitivity(sens, output_type = "all") out$table ## End(Not run)
Produces five types of visualization for climasus_spacetime_bayes and
climasus_spacetime_exceedance objects returned by
sus_mod_spacetime_bayes() and sus_mod_spacetime_exceedance():
choropleth maps of relative risk, temporal trend charts, space-time
interaction heatmaps, exceedance probability maps, and fixed-effect forest
plots. Static ggplot2 output is returned by default; set
interactive = TRUE for plotly::ggplotly() output.
sus_mod_plot_spacetime( x, type = c("rr_map", "temporal", "interaction", "exceedance", "coef"), municipalities = NULL, time_point = NULL, time_range = NULL, threshold = 1, facet_time = FALSE, palette = "RdYlBu", title = NULL, base_size = 11, interactive = FALSE, lang = "pt", ... )sus_mod_plot_spacetime( x, type = c("rr_map", "temporal", "interaction", "exceedance", "coef"), municipalities = NULL, time_point = NULL, time_range = NULL, threshold = 1, facet_time = FALSE, palette = "RdYlBu", title = NULL, base_size = 11, interactive = FALSE, lang = "pt", ... )
x |
A |
type |
Character. One of |
municipalities |
An |
time_point |
Integer or |
time_range |
Integer vector of length 2 ( |
threshold |
Numeric. RR threshold used to select the exceedance layer
from |
facet_time |
Logical. When |
palette |
Character. Name of a diverging RColorBrewer palette for RR
maps (e.g. |
title |
Character or |
base_size |
Numeric. Base font size for ggplot2 themes. Default |
interactive |
Logical. |
lang |
Character. Language for axis labels and titles: |
... |
Currently unused; reserved for future arguments. |
A ggplot object (or plotly object when interactive = TRUE).
type)"rr_map"Choropleth map of the posterior mean relative risk
(rr_mean) merged with the municipalities sf polygon layer.
Uses a diverging colour scale centred at 1.0. Municipalities where
the entire 95\
Supply time_point to show a single period; set facet_time = TRUE
to produce one facet per period; leave both as defaults to display the
mean across all periods. Requires municipalities.
"temporal"Line chart of the population-averaged posterior mean
RR (aggregated across municipalities) with a shaded 95\
interval ribbon over time. Supply time_range to restrict the
displayed periods.
"interaction"Tile heatmap of the space-time interaction term
(gamma_mean) with municipalities on the y-axis and time periods on
the x-axis. Requires x$interaction in the input object. Supply
time_range to restrict columns.
"exceedance"Choropleth map of the exceedance probability
P(RR > threshold). Requires a climasus_spacetime_exceedance
object (or a climasus_spacetime_bayes that has an $exceedance
slot). Requires municipalities.
"coef"Horizontal forest plot of the fixed-effect posterior
summaries (x$fixed). A dashed vertical reference line marks zero.
Knorr-Held, L. (2000). Bayesian modelling of inseparable space-time variation in disease risk. Statistics in Medicine, 19(17-18), 2555-2567. doi:10.1002/sim.1030
Blangiardo, M. & Cameletti, M. (2015). Spatial and Spatio-temporal Bayesian Models with R-INLA. Wiley. doi:10.1002/9781118950203
sus_mod_spacetime_bayes(), sus_mod_spacetime_exceedance(),
sus_mod_plot_spatial_bayes()
## Not run: library(climasus4r) library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) fit <- sus_mod_spacetime_bayes( df = agg, outcome = "deaths", covariates = c("temp_mean", "prec_total"), offset = "expected" ) # Choropleth map: mean RR across all periods sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map") # Choropleth for a single period (t = 3) sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map", time_point = 3L) # Faceted map sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map", facet_time = TRUE) # Temporal trend sus_mod_plot_spacetime(fit, type = "temporal", lang = "en") # Space-time interaction heatmap sus_mod_plot_spacetime(fit, type = "interaction") # Exceedance probability (requires climasus_spacetime_exceedance input) exc <- sus_mod_spacetime_exceedance(fit, thresholds = c(1.0, 1.5, 2.0)) sus_mod_plot_spacetime(exc, municipalities = shp, type = "exceedance", threshold = 1.5) # Fixed-effect forest plot sus_mod_plot_spacetime(fit, type = "coef", lang = "en") ## End(Not run)## Not run: library(climasus4r) library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) fit <- sus_mod_spacetime_bayes( df = agg, outcome = "deaths", covariates = c("temp_mean", "prec_total"), offset = "expected" ) # Choropleth map: mean RR across all periods sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map") # Choropleth for a single period (t = 3) sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map", time_point = 3L) # Faceted map sus_mod_plot_spacetime(fit, municipalities = shp, type = "rr_map", facet_time = TRUE) # Temporal trend sus_mod_plot_spacetime(fit, type = "temporal", lang = "en") # Space-time interaction heatmap sus_mod_plot_spacetime(fit, type = "interaction") # Exceedance probability (requires climasus_spacetime_exceedance input) exc <- sus_mod_spacetime_exceedance(fit, thresholds = c(1.0, 1.5, 2.0)) sus_mod_plot_spacetime(exc, municipalities = shp, type = "exceedance", threshold = 1.5) # Fixed-effect forest plot sus_mod_plot_spacetime(fit, type = "coef", lang = "en") ## End(Not run)
Produces three types of visualization for a climasus_spatial_bayes object
returned by sus_mod_spatial_bayes(): a relative risk choropleth map,
a credible interval width (uncertainty) choropleth, a forest plot of fixed
effects, or a combined panel of both maps.
sus_mod_plot_spatial_bayes( x, municipalities = NULL, type = c("rr", "uncertainty", "coef", "both"), title = NULL, base_size = 12, lang = "pt", ... )sus_mod_plot_spatial_bayes( x, municipalities = NULL, type = c("rr", "uncertainty", "coef", "both"), title = NULL, base_size = 12, lang = "pt", ... )
x |
A |
municipalities |
An |
type |
Character. One of |
title |
Character or |
base_size |
Numeric. Base font size passed to ggplot2 themes. Default
|
lang |
Character. Language for axis labels and titles: |
... |
Currently unused; reserved for future arguments. |
For type = "rr", "uncertainty", "coef": a ggplot object.
For type = "both": a patchwork object when patchwork is
installed, otherwise a named list with elements $rr and $uncertainty.
type)"rr"Choropleth map of the smoothed posterior mean relative risk
(rr_mean). Uses a diverging colour scale centred at 1.0 (navy = below,
white = 1.0, red = above). Municipalities where the entire 95\
interval lies above 1 (rr_lower95 > 1) receive a black border to flag
significantly elevated risk.
"uncertainty"Choropleth of the 95\
(rr_upper95 - rr_lower95), rendered with the plasma palette from
ggplot2::scale_fill_viridis_c(). Highlights areas with high posterior
uncertainty, often due to small populations or sparse data.
"coef"Horizontal forest plot of the fixed-effect posterior
summaries stored in x$fixed. A dashed vertical reference line marks
zero. Points show the posterior mean; horizontal bars show the 95\
credible interval.
"both"Side-by-side panel combining the "rr" and
"uncertainty" maps. Uses patchwork when available; falls back to
a named list with $rr and $uncertainty otherwise.
sus_mod_spatial_bayes(), sus_mod_spatial_weights()
## Not run: library(climasus4r) library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) W <- sus_mod_spatial_weights(shp, return_matrix = TRUE) result <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths" ) # Relative risk map sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "rr") # Uncertainty map sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "uncertainty") # Forest plot of fixed effects sus_mod_plot_spatial_bayes(result, type = "coef", lang = "en") # Combined panel (requires patchwork) sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "both") ## End(Not run)## Not run: library(climasus4r) library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) W <- sus_mod_spatial_weights(shp, return_matrix = TRUE) result <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths" ) # Relative risk map sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "rr") # Uncertainty map sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "uncertainty") # Forest plot of fixed effects sus_mod_plot_spatial_bayes(result, type = "coef", lang = "en") # Combined panel (requires patchwork) sus_mod_plot_spatial_bayes(result, municipalities = shp, type = "both") ## End(Not run)
Produces a choropleth LISA cluster map and/or a Moran scatter plot from a
climasus_spatial_moran object returned by sus_mod_spatial_moran().
sus_mod_plot_spatial_moran( x, municipalities = NULL, type = c("map", "scatter", "both"), alpha = 0.05, title = NULL, lang = "pt", ... )sus_mod_plot_spatial_moran( x, municipalities = NULL, type = c("map", "scatter", "both"), alpha = 0.05, title = NULL, lang = "pt", ... )
x |
A |
municipalities |
An |
type |
Character. Which panel(s) to produce. One of |
alpha |
Numeric in (0, 1). Significance level used for the subtitle
annotation. Default |
title |
Character or |
lang |
Character. Output language: |
... |
Additional arguments passed to |
type = "map" -> a ggplot object.
type = "scatter" -> a ggplot object.
type = "both" -> a patchwork / ggplot combined object, or a named
list list(map = <ggplot>, scatter = <ggplot>) if patchwork is not
installed.
type)
type |
Description |
"map" |
Choropleth map coloured by LISA quadrant (HH/LL/HL/LH/NS). |
"scatter" |
Moran scatter plot of standardised values vs. spatial lag. |
"both" |
Side-by-side panels via patchwork (named list fallback if not installed). |
Quadrant colours follow the conventional LISA palette: HH = "red3",
LL = "blue3", HL = "darkorange", LH = "steelblue", NS = "grey80".
sus_mod_spatial_moran(), sus_mod_spatial_weights()
## Not run: # Requires spdep, sf, ggplot2 (and optionally patchwork) library(climasus4r) # moran_res <- sus_mod_spatial_moran(df, "deaths", W) # shp <- geobr::read_municipality(code_muni = "all", year = 2020) sus_mod_plot_spatial_moran(moran_res, municipalities = shp, type = "both") sus_mod_plot_spatial_moran(moran_res, municipalities = shp, type = "map", lang = "en") sus_mod_plot_spatial_moran(moran_res, type = "scatter", lang = "es") ## End(Not run)## Not run: # Requires spdep, sf, ggplot2 (and optionally patchwork) library(climasus4r) # moran_res <- sus_mod_spatial_moran(df, "deaths", W) # shp <- geobr::read_municipality(code_muni = "all", year = 2020) sus_mod_plot_spatial_moran(moran_res, municipalities = shp, type = "both") sus_mod_plot_spatial_moran(moran_res, municipalities = shp, type = "map", lang = "en") sus_mod_plot_spatial_moran(moran_res, type = "scatter", lang = "es") ## End(Not run)
Renders a choropleth map from a climasus_spatial_scan object produced by
sus_mod_spatial_scan(). Each municipality polygon is coloured either by
its cluster's Relative Risk (RR, continuous diverging scale) or by a
categorical cluster label, making it straightforward to communicate the
location, extent, and intensity of spatial health clusters.
sus_mod_plot_spatial_scan( x, municipalities, show_rr = TRUE, alpha = 0.05, title = NULL, lang = "pt", ... )sus_mod_plot_spatial_scan( x, municipalities, show_rr = TRUE, alpha = 0.05, title = NULL, lang = "pt", ... )
x |
A |
municipalities |
An |
show_rr |
Logical. |
alpha |
Numeric in (0, 1). Significance threshold used to decide
which cluster borders to emphasise. Must match the value used when
running |
title |
Character or |
lang |
Character. Output language: |
... |
Currently unused; reserved for future extensions. |
A ggplot object. Assign to a variable to modify further or pass
to ggplot2::ggsave().
When show_rr = TRUE (default), the fill variable is the numeric RR of the
cluster that each municipality belongs to. Background municipalities
(cluster_id == 0) receive NA and are rendered in "grey80". A
diverging gradient (navy to white to red) centred on RR = 1 is used.
Municipalities belonging to a significant cluster (p-value < alpha)
additionally receive a thicker border (linewidth = 1.5) to distinguish
them from the most-likely cluster when it is not itself significant.
When show_rr = FALSE, municipalities are filled with categorical colours:
the most-likely cluster, up to nine secondary clusters, and the background
each receive a distinct colour via ggplot2::scale_fill_manual().
sus_mod_spatial_scan(), sus_spatial_join(),
sus_mod_plot_vulnerability()
## Not run: library(geobr) library(dplyr) muni_sf <- geobr::read_municipality(code_muni = 31, year = 2020) muni_sf <- dplyr::rename(muni_sf, code_muni = code_muni) set.seed(1) df_cases <- tibble::tibble( code_muni = as.character(muni_sf$code_muni), cases = rpois(nrow(muni_sf), 5), population = sample(5000:200000, nrow(muni_sf), replace = TRUE) ) result <- sus_mod_spatial_scan( df = df_cases, cases = "cases", population = "population", municipalities = muni_sf, n_simulations = 199L, lang = "pt" ) # Continuous RR map (default) sus_mod_plot_spatial_scan(result, municipalities = muni_sf, lang = "pt") # Categorical cluster-membership map sus_mod_plot_spatial_scan(result, municipalities = muni_sf, show_rr = FALSE, lang = "en") ## End(Not run)## Not run: library(geobr) library(dplyr) muni_sf <- geobr::read_municipality(code_muni = 31, year = 2020) muni_sf <- dplyr::rename(muni_sf, code_muni = code_muni) set.seed(1) df_cases <- tibble::tibble( code_muni = as.character(muni_sf$code_muni), cases = rpois(nrow(muni_sf), 5), population = sample(5000:200000, nrow(muni_sf), replace = TRUE) ) result <- sus_mod_spatial_scan( df = df_cases, cases = "cases", population = "population", municipalities = muni_sf, n_simulations = 199L, lang = "pt" ) # Continuous RR map (default) sus_mod_plot_spatial_scan(result, municipalities = muni_sf, lang = "pt") # Categorical cluster-membership map sus_mod_plot_spatial_scan(result, municipalities = muni_sf, show_rr = FALSE, lang = "en") ## End(Not run)
Produces radar (spider), matrix (2×2 SWOT board), and bar charts from a
climasus_swot object returned by sus_mod_swot().
sus_mod_plot_swot( x, type = c("radar", "matrix", "bar"), output_type = c("plot", "table", "all"), interactive = FALSE, entities = NULL, top_n = 3L, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_swot( x, type = c("radar", "matrix", "bar"), output_type = c("plot", "table", "all"), interactive = FALSE, entities = NULL, top_n = 3L, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. Convert the ggplot2 output to an interactive
plotly widget. Default |
entities |
Character vector or |
top_n |
Integer. For |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" → a ggplot or plotly object.
"table" → a tibble of the plotted data.
"all" → a named list $plot, $table.
type)
type |
Description |
"radar" |
Spider/radar chart of the four quadrant scores (0–100) per entity |
"matrix" |
Classic 2×2 SWOT board: score, category label, and top indicators for each quadrant. Best for a single entity. |
"bar" |
Grouped horizontal bars comparing all four quadrant scores per entity |
sus_mod_swot(), sus_mod_plot_vulnerability()
## Not run: swot <- sus_mod_swot(vulnerability = vi, af = af_res, lang = "pt") sus_mod_plot_swot(swot, type = "matrix", lang = "pt") sus_mod_plot_swot(swot, type = "radar", lang = "en") sus_mod_plot_swot(swot, type = "bar", interactive = TRUE) out <- sus_mod_plot_swot(swot, output_type = "all") ## End(Not run)## Not run: swot <- sus_mod_swot(vulnerability = vi, af = af_res, lang = "pt") sus_mod_plot_swot(swot, type = "matrix", lang = "pt") sus_mod_plot_swot(swot, type = "radar", lang = "en") sus_mod_plot_swot(swot, type = "bar", interactive = TRUE) out <- sus_mod_plot_swot(swot, output_type = "all") ## End(Not run)
Produces city vulnerability rankings, IPCC pillar decompositions, and Lorenz
concentration curves from a climasus_vi object returned by
sus_mod_vulnerability_index().
sus_mod_plot_vulnerability( x, type = c("ranking", "pillars", "lorenz"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )sus_mod_plot_vulnerability( x, type = c("ranking", "pillars", "lorenz"), output_type = c("plot", "table", "all"), interactive = FALSE, base_size = 12L, save_plot = NULL, lang = c("pt", "en", "es"), verbose = FALSE )
x |
A |
type |
Character. Plot type: |
output_type |
Character. |
interactive |
Logical. |
base_size |
Numeric. ggplot2 base font size. Default |
save_plot |
Character or |
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
Depending on output_type:
"plot" -> a ggplot or plotly object.
"table" -> a tibble of the plotted data.
"all" -> a named list: $plot, $table, $data.
type)
type |
Description |
"ranking" |
Horizontal lollipop of VI score per city, most vulnerable at top |
"pillars" |
Stacked horizontal bar of exposure/sensitivity/AC pillar scores |
"lorenz" |
Lorenz concentration curve of VI inequality across cities |
sus_mod_vulnerability_index(), sus_mod_plot_dlnm()
## Not run: vi <- sus_mod_vulnerability_index(exposure_df = exp_df, lang = "pt") sus_mod_plot_vulnerability(vi, type = "ranking", lang = "pt") sus_mod_plot_vulnerability(vi, type = "pillars", lang = "en") sus_mod_plot_vulnerability(vi, type = "lorenz", lang = "es") out <- sus_mod_plot_vulnerability(vi, output_type = "all") out$table ## End(Not run)## Not run: vi <- sus_mod_vulnerability_index(exposure_df = exp_df, lang = "pt") sus_mod_plot_vulnerability(vi, type = "ranking", lang = "pt") sus_mod_plot_vulnerability(vi, type = "pillars", lang = "en") sus_mod_plot_vulnerability(vi, type = "lorenz", lang = "es") out <- sus_mod_plot_vulnerability(vi, output_type = "all") out$table ## End(Not run)
Performs a two-stage multivariate meta-analysis to pool Distributed Lag
Non-linear Model (DLNM) estimates across multiple cities or regions.
Stage 1 city-specific estimates (coefficients and variance-covariance matrices
from sus_mod_dlnm()) are combined using multivariate random-effects
meta-analysis via mvmeta, producing pooled exposure-response and
lag-response curves, heterogeneity statistics, and Best Linear Unbiased
Predictors (BLUPs) for each city.
sus_mod_pool( fits, exposure_range = NULL, n_grid = 100L, pred_at = c(0.75, 0.9, 0.95, 0.99), blup = TRUE, method = "reml", lang = "pt", verbose = TRUE )sus_mod_pool( fits, exposure_range = NULL, n_grid = 100L, pred_at = c(0.75, 0.9, 0.95, 0.99), blup = TRUE, method = "reml", lang = "pt", verbose = TRUE )
fits |
A named list of |
exposure_range |
Numeric vector of length 2 specifying the exposure
grid range for the pooled prediction. Default |
n_grid |
Integer. Number of exposure grid points for the pooled
prediction curve. Default |
pred_at |
Numeric vector of quantile probabilities (0-1) for the
pooled exposure-response summary table. Default |
blup |
Logical. Compute BLUP city-specific predictions? Default |
method |
Character. |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_pool list with components:
mvmeta_fitThe raw mvmeta model object.
pooled_preddlnm::crosspred object with pooled coefficients.
exposure_responseTibble of pooled RR at quantile grid points.
lag_responseTibble of pooled RR by lag at the 75th percentile exposure.
blup_predsNamed list of city-specific BLUP crosspred objects
(when blup = TRUE).
city_tableTibble with one row per city showing city-specific and BLUP-adjusted RRs at the 75th percentile.
heterogeneityTibble with Cochran Q, df, p-value, and I^2 statistics.
metaList of metadata: climate_col, outcome_col, lag_max,
n_cities, city_names, method, argvar, arglag, ref_value,
pred_at, call_time.
Let be the -dimensional vector of
cross-basis coefficients for city , estimated with variance
. The multivariate random-effects model is:
where is the between-city covariance matrix estimated by
REML. The pooled estimate and its
variance are passed to dlnm::crosspred() to produce a pooled
exposure-response surface identical in format to the single-city output.
BLUPs shrink city-specific estimates toward the pooled mean:
## Not run: fits <- list( city_a = sus_mod_dlnm(df_a, ...), city_b = sus_mod_dlnm(df_b, ...), city_c = sus_mod_dlnm(df_c, ...) ) pool <- sus_mod_pool(fits, lang = "en") print(pool) plot_pool <- sus_mod_plot_dlnm(pool, lang = "en") ## End(Not run)## Not run: fits <- list( city_a = sus_mod_dlnm(df_a, ...), city_b = sus_mod_dlnm(df_b, ...), city_c = sus_mod_dlnm(df_c, ...) ) pool <- sus_mod_pool(fits, lang = "en") print(pool) plot_pool <- sus_mod_plot_dlnm(pool, lang = "en") ## End(Not run)
Compares exposure-response curves and cumulative relative risks across
population strata (e.g., age groups, sexes, income quintiles, municipalities)
to identify which subgroups are most sensitive to a climate exposure.
Takes a named list of climasus_dlnm fits — one per stratum — and extracts
the cumulative RR at user-specified hot and cold percentiles for each,
producing a ranked comparison table and full stratum-specific ERCs for
plotting.
sus_mod_sensitivity( fits, hot_percentile = 0.99, cold_percentile = 0.01, stratum_labels = NULL, alpha = 0.05, lang = "pt", verbose = TRUE )sus_mod_sensitivity( fits, hot_percentile = 0.99, cold_percentile = 0.01, stratum_labels = NULL, alpha = 0.05, lang = "pt", verbose = TRUE )
fits |
A named list of |
hot_percentile |
Numeric in (0, 1). Quantile of the observed exposure
distribution used as the "hot" comparison point. Default: |
cold_percentile |
Numeric in (0, 1). Quantile of the observed exposure
distribution used as the "cold" comparison point. Default: |
stratum_labels |
Named character vector or |
alpha |
Numeric. Significance level for confidence intervals.
Default: |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
A climasus_sensitivity list with:
$rr_tableTibble with one row per (stratum, component):
stratum, label, component ("hot" or "cold"),
quantile_prob, exposure, rr, rr_lo, rr_hi, ref_exposure.
$comparisonTibble ranked by sensitivity_index (descending):
one row per stratum with hot_rr, hot_rr_lo, hot_rr_hi,
cold_rr, cold_rr_lo, cold_rr_hi, sensitivity_index,
hot_rank, cold_rank.
$stratum_curvesTibble with the full exposure-response curve
for each stratum (100-point grid from each $pred): columns
stratum, label, exposure, rr, rr_lo, rr_hi. Suitable
for overlaid ERC plots.
$metaList: climate_col, n_strata, stratum_names,
hot_percentile, cold_percentile, alpha, call_time.
For each stratum with fitted DLNM , the cumulative
RR at exposure quantile (relative to the stratum's reference
) is:
where is the -th quantile of the observed
exposure distribution in stratum . RRs are extracted by linear
interpolation from the pre-computed dlnm::crosspred grid stored in
each climasus_dlnm object — no re-fitting or additional dlnm calls
are needed.
The sensitivity index for stratum is defined as:
a combined measure of total climate-attributable vulnerability (heat + cold).
Baccini, M., et al. (2011). Heat effects on mortality in 15 European cities. Epidemiology, 22(1), 68-77. doi:10.1097/EDE.0b013e3181fdcd5e
Benmarhnia, T., et al. (2015). A difference-in-differences approach to assess the effect of a heat action plan on heat-related mortality, and differences in effectiveness according to sex, age, and socioeconomic status. Environmental Health Perspectives, 124(11), 1694-1699. doi:10.1289/ehp.1510173
Armstrong, B.G., et al. (2017). The role of humidity in associations of high temperature with mortality. Epidemiology, 28(6), 781-789.
sus_mod_dlnm(), sus_mod_af(), sus_mod_pool()
## Not run: # Fit separate DLNMs per age group fits <- list( elderly = sus_mod_dlnm(df_65plus, ...), adults = sus_mod_dlnm(df_1864, ...), youth = sus_mod_dlnm(df_under18, ...) ) sens <- sus_mod_sensitivity(fits, lang = "pt") print(sens) # ranked comparison table tidy(sens) # one-row-per-stratum tibble ## End(Not run)## Not run: # Fit separate DLNMs per age group fits <- list( elderly = sus_mod_dlnm(df_65plus, ...), adults = sus_mod_dlnm(df_1864, ...), youth = sus_mod_dlnm(df_under18, ...) ) sens <- sus_mod_sensitivity(fits, lang = "pt") print(sens) # ranked comparison table tidy(sens) # one-row-per-stratum tibble ## End(Not run)
Fits a full Bayesian spatiotemporal hierarchical model using INLA
(Integrated Nested Laplace Approximation). The model decomposes disease
risk into structured spatial effects (BYM2, BYM, Besag, or IID), structured
temporal effects (RW1, RW2, AR1, or IID), and optionally a space-time
interaction following the four Knorr-Held (2000) interaction types.
Climate and environmental covariates from a climasus_df can be included
as fixed effects.
sus_mod_spacetime_bayes( df, outcome, W, time_col = "date", time_unit = c("year", "month", "week", "auto"), covariates = NULL, offset = NULL, family = c("poisson", "nbinomial", "binomial", "gaussian"), spatial_model = c("bym2", "bym", "besag", "iid"), temporal_model = c("rw1", "rw2", "ar1", "iid_time"), interaction_type = c("none", "I", "II", "III", "IV"), pc_prior_u = 0.5, pc_prior_alpha = 0.01, compute_waic = TRUE, compute_cpo = FALSE, exceedance_threshold = 1, n_samples = 1000L, seed = 42L, lang = "pt", verbose = TRUE )sus_mod_spacetime_bayes( df, outcome, W, time_col = "date", time_unit = c("year", "month", "week", "auto"), covariates = NULL, offset = NULL, family = c("poisson", "nbinomial", "binomial", "gaussian"), spatial_model = c("bym2", "bym", "besag", "iid"), temporal_model = c("rw1", "rw2", "ar1", "iid_time"), interaction_type = c("none", "I", "II", "III", "IV"), pc_prior_u = 0.5, pc_prior_alpha = 0.01, compute_waic = TRUE, compute_cpo = FALSE, exceedance_threshold = 1, n_samples = 1000L, seed = 42L, lang = "pt", verbose = TRUE )
df |
A |
outcome |
Character. Name of the response (count) column in |
W |
A |
time_col |
Character. Name of the column containing time information.
Can be a |
time_unit |
Character. Temporal aggregation unit used to build the
integer time index. One of |
covariates |
Character vector of covariate column names in |
offset |
Character. Name of a population or expected counts column
in |
family |
Character. Likelihood family. One of |
spatial_model |
Character. Spatial random effect structure. One of
|
temporal_model |
Character. Temporal random effect structure. One of
|
interaction_type |
Character. Space-time interaction type following
Knorr-Held (2000). One of |
pc_prior_u |
Positive numeric. PC prior parameter |
pc_prior_alpha |
Numeric in (0, 1). PC prior parameter |
compute_waic |
Logical. If |
compute_cpo |
Logical. If |
exceedance_threshold |
Positive numeric. Compute |
n_samples |
Positive integer. Number of posterior samples drawn via
|
seed |
Integer. Random seed for reproducibility. Default |
lang |
Character. Language for CLI messages: |
verbose |
Logical. If |
A named list of class c("climasus_spacetime_bayes", "list") with
the following slots:
$fixeddata.frame with columns term, mean, sd,
lower95, upper95, mode (posterior fixed-effect summaries).
$rrdata.frame with columns code_muni, time_idx,
rr_mean, rr_lower95, rr_upper95, p_exceed (relative risk
per space-time cell with exceedance probability).
$spatial_redata.frame with columns code_muni, phi_mean,
phi_sd (posterior summaries of structured spatial random effect).
$temporal_redata.frame with columns time_idx, psi_mean,
psi_sd (posterior summaries of structured temporal random effect).
$interaction_redata.frame with columns code_muni,
time_idx, gamma_mean, gamma_sd, or NULL if
interaction_type = "none".
$fittedNumeric vector of posterior mean fitted values (response scale).
$waicNamed list with $waic (scalar) and $p_eff (effective
number of parameters), or NULL if compute_waic = FALSE.
$dicNamed list with $dic (scalar) and $p_d (effective
parameters), or NULL.
$model_specNamed list with $spatial_model,
$temporal_model, $interaction_type, $family.
$callThe matched call.
$n_areasInteger. Number of unique municipalities.
$n_timesInteger. Number of unique time periods.
The linear predictor for area at time is:
where is the spatial random effect, the temporal
random effect, the optional space-time interaction, and
the expected counts offset.
"bym2"BYM2 model (Riebler et al. 2016): scaled ICAR + IID with a single precision and a mixing parameter. Recommended for disease mapping. PC priors applied.
"bym"Original BYM model (Besag, York & Mollie 1991): ICAR + independent Gaussian components with separate precision parameters.
"besag"Intrinsic CAR (Besag 1974): purely structured spatial random effect.
"iid"Independent normal random effects (no spatial structure).
"none"No space-time interaction.
"I"IID interaction: .
"II"Structured in time, unstructured in space: separate RW1 per area.
"III"Structured in space, unstructured in time: separate ICAR per time period.
"IV"Structured in both space and time (inseparable interaction).
For the BYM2 spatial model, penalised-complexity (PC) priors are used
for the precision hyperparameter: where
pc_prior_u and pc_prior_alpha control the tail probability. Default
values u = 0.5, alpha = 0.01 are weakly informative and suitable for
standardised disease mapping.
Knorr-Held, L. (2000). Bayesian modelling of inseparable space-time variation in disease risk. Statistics in Medicine, 19(17-18), 2555-2567.
Riebler, A., Sorbye, 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 using integrated nested Laplace approximations. Journal of the Royal Statistical Society B, 71(2), 319-392.
Blangiardo, M., & Cameletti, M. (2015). Spatial and Spatio-temporal Bayesian Models with R-INLA. Wiley.
Besag, J., York, J., & Mollie, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43(1), 1-20.
sus_mod_spatial_weights() to build the required adjacency object,
sus_mod_spatial_bayes() for purely cross-sectional spatial Bayesian
models (CARBayes), sus_mod_dlnm() for time-series DLNM models.
## Not run: library(climasus4r) library(geobr) # Build spatial weights for Rio Grande do Norte shp <- geobr::read_municipality(code_muni = "RN", year = 2022) W <- sus_mod_spatial_weights(shp, return_matrix = TRUE) # Prepare aggregated health-climate panel data (areas x time periods) # agg <- sus_data_aggregate(cleaned_df) |> # sus_climate_inmet() |> # sus_climate_aggregate(temporal_strategy = "exact") # BYM2 spatiotemporal model with Poisson family result <- sus_mod_spacetime_bayes( df = agg, outcome = "deaths", W = W, time_col = "date", time_unit = "month", covariates = c("temp_mean", "prec_total"), offset = "population", family = "poisson", spatial_model = "bym2", temporal_model = "rw1", interaction_type = "I", pc_prior_u = 0.5, pc_prior_alpha = 0.01, compute_waic = TRUE, n_samples = 1000L, seed = 42L, lang = "pt" ) print(result) result$fixed result$rr result$spatial_re result$temporal_re result$waic ## End(Not run)## Not run: library(climasus4r) library(geobr) # Build spatial weights for Rio Grande do Norte shp <- geobr::read_municipality(code_muni = "RN", year = 2022) W <- sus_mod_spatial_weights(shp, return_matrix = TRUE) # Prepare aggregated health-climate panel data (areas x time periods) # agg <- sus_data_aggregate(cleaned_df) |> # sus_climate_inmet() |> # sus_climate_aggregate(temporal_strategy = "exact") # BYM2 spatiotemporal model with Poisson family result <- sus_mod_spacetime_bayes( df = agg, outcome = "deaths", W = W, time_col = "date", time_unit = "month", covariates = c("temp_mean", "prec_total"), offset = "population", family = "poisson", spatial_model = "bym2", temporal_model = "rw1", interaction_type = "I", pc_prior_u = 0.5, pc_prior_alpha = 0.01, compute_waic = TRUE, n_samples = 1000L, seed = 42L, lang = "pt" ) print(result) result$fixed result$rr result$spatial_re result$temporal_re result$waic ## End(Not run)
Given a fitted climasus_spacetime_bayes object, computes for each
municipality time cell the posterior probability that the
relative risk (RR) exceeds one or more critical thresholds:
.
Exceedance probabilities are a cornerstone of Bayesian disease surveillance
because they translate uncertain posterior estimates into decision-relevant
quantities. For example, can trigger an alert for
a municipality in a given week, whereas the raw posterior mean alone may
understate uncertainty.
sus_mod_spacetime_exceedance( fit, thresholds = c(1, 1.5, 2), aggregate_time = NULL, municipalities = NULL, lang = "pt", verbose = TRUE )sus_mod_spacetime_exceedance( fit, thresholds = c(1, 1.5, 2), aggregate_time = NULL, municipalities = NULL, lang = "pt", verbose = TRUE )
fit |
A |
thresholds |
Numeric vector of positive RR thresholds for which
|
aggregate_time |
Character or |
municipalities |
An |
lang |
Character. Language for CLI messages: |
verbose |
Logical. If |
A named list of class c("climasus_spacetime_exceedance", "list")
with the following slots:
$exceedancedata.frame with columns code_muni,
time_idx (or time_period if aggregated), rr_mean, and one
p_gt_X column per threshold (e.g. p_gt_1_0, p_gt_1_5,
p_gt_2_0).
$thresholdsNumeric vector of thresholds used.
$n_exceeddata.frame with columns threshold and
n_cells_exceed counting how many cells have
.
$callThe matched call.
Exact computation requires access to the full MCMC sample or INLA posterior
marginals. When only the posterior mean and 95\
stored (as in the $rr slot), exceedance probabilities are approximated
via a log-normal approximation:
where is the standard normal CDF. This is equivalent to assuming
that is approximately normally distributed in the posterior,
which is a standard approximation for count-data hierarchical models
(Richardson et al., 2004).
For exact computation when the full posterior is available, use
INLA::inla.pmarginal() on the fitted INLA marginals directly.
When aggregate_time is "year" or "month", the function averages
and across cells within
each municipality time period, then recomputes exceedance
probabilities for the aggregated values. This is appropriate for
surveillance summaries but not for causal inference.
Richardson, S., Thomson, A., Best, N., & Elliott, P. (2004). Interpreting posterior relative risk estimates in disease-mapping studies. Environmental Health Perspectives, 112(9), 1016-1025.
Lawson, A. B. (2018). Bayesian Disease Mapping: Hierarchical Modeling in Spatial Epidemiology (3rd ed.). CRC Press.
Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
sus_mod_spacetime_bayes() to fit the spatiotemporal Bayesian model,
sus_mod_spatial_bayes() for the purely spatial (cross-sectional) version,
sus_mod_spatial_moran() for exploratory spatial autocorrelation analysis.
## Not run: library(climasus4r) # Fit a spatiotemporal Bayesian model (requires climasus_spacetime_bayes) # fit <- sus_mod_spacetime_bayes(df = agg, outcome = "deaths", ...) # Compute exceedance probabilities for RR thresholds 1.0, 1.5, and 2.0 exc <- sus_mod_spacetime_exceedance( fit = fit, thresholds = c(1.0, 1.5, 2.0), lang = "pt" ) print(exc) head(exc$exceedance) exc$n_exceed # Aggregate to annual exceedances and join municipality geometry library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) exc_annual <- sus_mod_spacetime_exceedance( fit = fit, thresholds = c(1.0, 1.5, 2.0), aggregate_time = "year", municipalities = shp, lang = "pt" ) ## End(Not run)## Not run: library(climasus4r) # Fit a spatiotemporal Bayesian model (requires climasus_spacetime_bayes) # fit <- sus_mod_spacetime_bayes(df = agg, outcome = "deaths", ...) # Compute exceedance probabilities for RR thresholds 1.0, 1.5, and 2.0 exc <- sus_mod_spacetime_exceedance( fit = fit, thresholds = c(1.0, 1.5, 2.0), lang = "pt" ) print(exc) head(exc$exceedance) exc$n_exceed # Aggregate to annual exceedances and join municipality geometry library(geobr) shp <- geobr::read_municipality(code_muni = "all", year = 2022) exc_annual <- sus_mod_spacetime_exceedance( fit = fit, thresholds = c(1.0, 1.5, 2.0), aggregate_time = "year", municipalities = shp, lang = "pt" ) ## End(Not run)
Produces approximate predictions at new or future space-time points from a
climasus_spacetime_bayes object fitted by sus_mod_spacetime_bayes().
This function is designed for disease surveillance projections and
counterfactual scenario analysis (e.g. "what if temperature was 2 °C
higher?").
sus_mod_spacetime_predict( fit, newdata = NULL, horizon = 0L, covariates_new = NULL, include_ci = TRUE, return_samples = FALSE, lang = "pt", verbose = TRUE )sus_mod_spacetime_predict( fit, newdata = NULL, horizon = 0L, covariates_new = NULL, include_ci = TRUE, return_samples = FALSE, lang = "pt", verbose = TRUE )
fit |
A |
newdata |
A |
horizon |
Non-negative integer. Number of periods ahead to predict when
|
covariates_new |
Named list of covariate overrides for scenario
analysis. Each element must be a scalar (applied to all rows) or a vector
of length |
include_ci |
Logical. If |
return_samples |
Logical. If |
lang |
Character. Language for CLI messages: |
verbose |
Logical. If |
A named list of class c("climasus_spacetime_pred", "list") with:
$predictionsdata.frame with columns code_muni, time_idx,
pred_mean, and (if include_ci = TRUE) pred_lower95,
pred_upper95.
$n_predictedInteger. Total number of predicted observations.
$horizonInteger. Horizon used (0 when newdata is supplied).
$callThe matched call.
If return_samples = TRUE and INLA is available, an additional
$samples slot contains raw INLA posterior samples (list from
INLA::inla.posterior.sample()).
Because re-running INLA for new data is computationally expensive, this function uses an approximate linear-predictor approach:
Extract posterior mean fixed effects and their standard
deviations from fit$fixed.
For new covariate matrix , compute the fixed-effect
contribution: .
Spatial random effect: reuse fit$spatial_re for municipalities present
in the fitted model. For municipalities not in the training data, the
spatial random effect is set to NA with a warning.
Temporal random effect: for in-sample time points, reuse fit$temporal_re
directly. For future periods (horizon > 0), extrapolate using the last
observed increment (RW1: repeat last increment; RW2: project second
differences) with uncertainty propagation.
Full linear predictor: .
Variance propagation:
where (diagonal approximation).
Point prediction: (Poisson / NB) or
(Gaussian).
95\
.
Important: this is an approximation. For exact posterior predictive
distributions, re-run sus_mod_spacetime_bayes() with the full dataset
including future periods.
covariates_new accepts a named list of scalar or vector overrides, e.g.:
covariates_new = list(temp_mean = new_grid$temp_mean + 2)
Overrides are applied to the resolved covariate matrix after newdata
columns are extracted, so they can reference vectors of length
nrow(newdata).
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.
Blangiardo, M., & Cameletti, M. (2015). Spatial and Spatio-temporal Bayesian Models with R-INLA. Wiley.
Held, L., & Schrödle, B. (2010). Posterior and cross-validatory predictive checks: a comparison of MCMC and INLA. In Statistical Modelling and Regression Structures (pp. 91-110). Physica-Verlag HD.
sus_mod_spatial_bayes() for cross-sectional Bayesian disease mapping,
sus_mod_spatial_weights() to build the spatial adjacency object,
sus_mod_spatial_moran() for exploratory spatial autocorrelation analysis.
## Not run: library(climasus4r) # Assume `st_fit` is a climasus_spacetime_bayes object # fitted on monthly data for 2015-2020 # 1. In-sample predictions for validation pred_insample <- sus_mod_spacetime_predict( fit = st_fit, newdata = training_data, lang = "pt" ) head(pred_insample$predictions) # 2. Out-of-sample: 6 months ahead pred_future <- sus_mod_spacetime_predict( fit = st_fit, horizon = 6L, lang = "en" ) pred_future$predictions # 3. Counterfactual: +2 degrees C scenario pred_counter <- sus_mod_spacetime_predict( fit = st_fit, newdata = new_grid, covariates_new = list(temp_mean = new_grid$temp_mean + 2), lang = "pt" ) ## End(Not run)## Not run: library(climasus4r) # Assume `st_fit` is a climasus_spacetime_bayes object # fitted on monthly data for 2015-2020 # 1. In-sample predictions for validation pred_insample <- sus_mod_spacetime_predict( fit = st_fit, newdata = training_data, lang = "pt" ) head(pred_insample$predictions) # 2. Out-of-sample: 6 months ahead pred_future <- sus_mod_spacetime_predict( fit = st_fit, horizon = 6L, lang = "en" ) pred_future$predictions # 3. Counterfactual: +2 degrees C scenario pred_counter <- sus_mod_spacetime_predict( fit = st_fit, newdata = new_grid, covariates_new = list(temp_mean = new_grid$temp_mean + 2), lang = "pt" ) ## End(Not run)
Fits a Bayesian hierarchical spatial model for disease mapping using
Conditional Autoregressive (CAR) priors implemented in the CARBayes
package, or the reparameterised BYM2 model via INLA. Four model
specifications are available: the Besag-York-Mollie (BYM) model with
structured and unstructured random effects, the Leroux model with a mixing
parameter for spatial dependence, the independent random effects model
(all via CARBayes/MCMC), and the BYM2 model (via INLA with penalised
complexity priors). Climate and environmental covariates stored in a
climasus_df can be passed directly as fixed effects.
sus_mod_spatial_bayes( df, outcome, W, covariates = NULL, offset = NULL, family = c("poisson", "binomial", "gaussian"), model = c("bym", "leroux", "independent", "bym2"), n_iter = 10000L, burnin = 2000L, thin = 10L, prior_tau2 = c(1, 0.01), seed = 42L, lang = "pt", verbose = TRUE )sus_mod_spatial_bayes( df, outcome, W, covariates = NULL, offset = NULL, family = c("poisson", "binomial", "gaussian"), model = c("bym", "leroux", "independent", "bym2"), n_iter = 10000L, burnin = 2000L, thin = 10L, prior_tau2 = c(1, 0.01), seed = 42L, lang = "pt", verbose = TRUE )
df |
A |
outcome |
Character. Name of the response variable column in |
W |
A |
covariates |
Character vector of covariate column names in |
offset |
Character. Name of an expected counts column in |
family |
Character. Response distribution. One of |
model |
Character. Spatial model structure. One of:
|
n_iter |
Positive integer. Total number of MCMC iterations
(including burn-in). Used only for CARBayes models ( |
burnin |
Positive integer. Number of initial MCMC iterations to
discard as burn-in. Must be less than |
thin |
Positive integer. Thinning interval. Used only for CARBayes
models. Default |
prior_tau2 |
Numeric vector of length 2. Shape and rate parameters of
the Inverse-Gamma prior for the variance of spatial random effects.
Used only for CARBayes models. Default |
seed |
Integer. Random seed passed to |
lang |
Character. Language for CLI messages: |
verbose |
Logical. If |
A named list of class c("climasus_spatial_bayes", "list") with
slots $fixed (posterior fixed effects), $random (spatial random
effects per municipality), $rr (posterior relative risk with 95\
credible intervals), $fitted (posterior mean fitted values), $dic
(Deviance Information Criterion; for BYM2 a named numeric with both DIC
and WAIC), $model, $family, $n_iter_effective, and $call.
Smoothed relative risks are computed as:
where are the posterior mean fitted counts and
are the expected counts (offset on the original scale). When no offset is
supplied, is set to the overall mean of the fitted values, which
is equivalent to a standardised mortality/morbidity ratio. Credible intervals
for the RR are derived from the 2.5th and 97.5th percentiles of the
MCMC samples for fitted values divided by the expected (CARBayes models), or
from the INLA marginal posterior quantiles (BYM2 model).
The BYM2 model of Riebler et al. (2016) reparameterises the original
Besag-York-Mollie model into a single precision parameter and
a mixing parameter that quantifies the proportion of
variance attributable to structured spatial variation. The latent field is:
where is the scaled ICAR component and .
Penalised complexity (PC) priors are placed on and :
and .
prior_tau2 specifies the shape and rate parameters of an
Inverse-Gamma prior for the variance component :
.
The default c(1, 0.01) is weakly informative. Fixed-effect coefficients
receive flat (improper) priors.
Besag, J., York, J., & Mollie, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43(1), 1-20.
Leroux, B. G., Lei, X., & Breslow, N. (2000). Estimation of disease rates in small areas: a new mixed model for spatial dependence. In Statistical Models in Epidemiology, the Environment, and Clinical Trials (pp. 179-191). Springer.
Lee, D. (2013). CARBayes: an R package for Bayesian spatial modelling with conditional autoregressive priors. Journal of Statistical Software, 55(13), 1-24.
Riebler, A., Sorbye, 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.
sus_mod_spatial_weights() to build the required adjacency object,
sus_mod_spatial_moran() for exploratory spatial autocorrelation,
sus_mod_spatial_scan() for cluster detection.
## Not run: library(climasus4r) library(geobr) # Build spatial weights for Nordeste shp <- geobr::read_municipality(code_muni = "all", year = 2022) shp_ne <- shp[shp$abbrev_state %in% c("CE", "RN", "PB", "PE"), ] W <- sus_mod_spatial_weights(shp_ne, return_matrix = TRUE) # Prepare aggregated health-climate data (must have code_muni) # agg <- sus_data_aggregate(cleaned_df) |> sus_climate_aggregate() # BYM Poisson model with temperature as covariate (CARBayes/MCMC) result_bym <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths", family = "poisson", model = "bym", n_iter = 10000, burnin = 2000, thin = 10, seed = 42, lang = "pt" ) print(result_bym) # BYM2 Poisson model with PC priors (INLA) - requires INLA package result_bym2 <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths", family = "poisson", model = "bym2", seed = 42, lang = "pt" ) print(result_bym2) result_bym2$rr result_bym2$fixed ## End(Not run)## Not run: library(climasus4r) library(geobr) # Build spatial weights for Nordeste shp <- geobr::read_municipality(code_muni = "all", year = 2022) shp_ne <- shp[shp$abbrev_state %in% c("CE", "RN", "PB", "PE"), ] W <- sus_mod_spatial_weights(shp_ne, return_matrix = TRUE) # Prepare aggregated health-climate data (must have code_muni) # agg <- sus_data_aggregate(cleaned_df) |> sus_climate_aggregate() # BYM Poisson model with temperature as covariate (CARBayes/MCMC) result_bym <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths", family = "poisson", model = "bym", n_iter = 10000, burnin = 2000, thin = 10, seed = 42, lang = "pt" ) print(result_bym) # BYM2 Poisson model with PC priors (INLA) - requires INLA package result_bym2 <- sus_mod_spatial_bayes( df = agg, outcome = "deaths", W = W, covariates = c("temp_mean", "prec_total"), offset = "expected_deaths", family = "poisson", model = "bym2", seed = 42, lang = "pt" ) print(result_bym2) result_bym2$rr result_bym2$fixed ## End(Not run)
Computes Moran's I global spatial autocorrelation statistic and Local Indicators of Spatial Association (LISA) for a numeric health outcome measured at municipality level. The global statistic tests whether the outcome is spatially clustered across the study region; the local statistics identify significant High-High (hotspots), Low-Low (coldspots), High-Low, and Low-High spatial outlier clusters.
sus_mod_spatial_moran( df, outcome, W, municipalities = NULL, permutations = 999L, alpha = 0.05, adjust_p = c("fdr", "bonferroni", "none"), lang = "pt", verbose = TRUE )sus_mod_spatial_moran( df, outcome, W, municipalities = NULL, permutations = 999L, alpha = 0.05, adjust_p = c("fdr", "bonferroni", "none"), lang = "pt", verbose = TRUE )
df |
A |
outcome |
Character. Name of the numeric outcome column in |
W |
A |
municipalities |
Optional character or integer vector of |
permutations |
Positive integer. Number of Monte Carlo permutations
for both global and local inference. Default |
alpha |
Numeric in (0, 1). Significance threshold applied to
p-adjusted local Moran p-values when assigning quadrant labels.
Default |
adjust_p |
Character. Method passed to |
lang |
Character. Output language for messages: |
verbose |
Logical. If |
An object of class c("climasus_spatial_moran", "list") with the
following named elements:
$globalOne-row data.frame with columns I, E.I,
Var.I, Z.I, p_value (analytical), and p_simulated
(permutation-based).
$localdata.frame with one row per spatial unit and columns
code_muni, Ii (local Moran statistic), Z.Ii (z-score),
p_raw (unit-level permutation p), p_adj (adjusted p), and
quadrant (factor: "HH", "LL", "HL", "LH", "NS").
$n_HHInteger. Number of significant HH (hotspot) units.
$n_LLInteger. Number of significant LL (coldspot) units.
$n_HLInteger. Number of significant HL spatial outlier units.
$n_LHInteger. Number of significant LH spatial outlier units.
$outcome_nameCharacter. The outcome argument value.
$callThe matched function call.
Moran's I is computed via permutation inference using
spdep::moran.mc(). The observed statistic is compared against the
empirical null distribution obtained by randomly permuting the outcome
values across spatial units. The reported p_simulated is the proportion
of permuted values as extreme as or more extreme than the observed I.
Local Moran statistics are computed via spdep::localmoran_perm(), which
uses conditional permutation to generate unit-specific null distributions.
Each observation is assigned a LISA quadrant based on its standardised
value and the standardised spatial lag:
HHHigh value surrounded by high neighbours (hotspot).
LLLow value surrounded by low neighbours (coldspot).
HLHigh value surrounded by low neighbours (spatial outlier).
LHLow value surrounded by high neighbours (spatial outlier).
NSNot significant at the specified alpha level.
Moran, P. A. P. (1950). Notes on continuous stochastic phenomena. Biometrika, 37(1-2), 17-23.
Anselin, L. (1995). Local indicators of spatial association—LISA. Geographical Analysis, 27(2), 93-115.
Bivand, R. S., Pebesma, E., & Gomez-Rubio, V. (2013). Applied Spatial Data Analysis with R (2nd ed.). Springer.
sus_mod_spatial_weights(), sus_spatial_join()
## Not run: # Requires spdep and a climasus_weights object W library(climasus4r) # W <- sus_mod_spatial_weights(shp, style = "W") result <- sus_mod_spatial_moran( df = my_df, outcome = "deaths", W = W, permutations = 999, alpha = 0.05, adjust_p = "fdr", lang = "pt" ) print(result) # Access local clusters result$local[result$local$quadrant == "HH", ] ## End(Not run)## Not run: # Requires spdep and a climasus_weights object W library(climasus4r) # W <- sus_mod_spatial_weights(shp, style = "W") result <- sus_mod_spatial_moran( df = my_df, outcome = "deaths", W = W, permutations = 999, alpha = 0.05, adjust_p = "fdr", lang = "pt" ) print(result) # Access local clusters result$local[result$local$quadrant == "HH", ] ## End(Not run)
Fits maximum-likelihood spatial regression models that account for spatial spillovers between geographic units (e.g. municipalities) in climate-health studies. Four model families are supported: the Spatial Autoregressive Model (SAR / spatial lag), the Spatial Error Model (SEM), the Spatial Durbin Model (SDM), and the Spatial Autocorrelation Model (SAC).
sus_mod_spatial_reg( df, formula, W, model = c("lag", "error", "durbin", "sac"), method = c("eigen", "LU", "Chebyshev", "MC"), zero_policy = TRUE, lang = "pt", verbose = TRUE )sus_mod_spatial_reg( df, formula, W, model = c("lag", "error", "durbin", "sac"), method = c("eigen", "LU", "Chebyshev", "MC"), zero_policy = TRUE, lang = "pt", verbose = TRUE )
df |
A |
formula |
A |
W |
A |
model |
Character. Spatial model family. One of |
method |
Character. Estimation method passed to the underlying
spatialreg function. One of |
zero_policy |
Logical. If |
lang |
Character. Output language for messages: |
verbose |
Logical. If |
An object of class c("climasus_spatial_reg", "list") with the
following named elements:
$modelCharacter. The model argument value.
$model_labelCharacter. Human-readable model name.
$coefficientsdata.frame with columns term, estimate,
std_error, z_value, p_value for all covariates (excluding
the spatial parameters rho/lambda).
$rhoNumeric spatial lag parameter (NULL for the error
model).
$lambdaNumeric spatial error parameter (NULL for the
lag and durbin models).
$impactsdata.frame with columns term, direct,
indirect, total (from spatialreg::impacts()), or NULL for
the error model or when impact computation fails.
$aicNumeric. AIC of the spatial model.
$lm_aicNumeric. AIC of the OLS baseline (same formula, same data).
$moran_residualsNamed list with elements I (Moran
statistic), p_value (analytical p-value), and z (z-score).
$fittedNumeric vector of fitted values.
$residualsNumeric vector of model residuals.
$callThe matched function call.
"lag" (SAR)The outcome in unit depends on a weighted average of outcomes
in neighbouring units (spatial lag). Estimated via
spatialreg::lagsarlm(). Contains a spatial lag parameter rho.
"error" (SEM)Spatial dependence enters through a spatially autocorrelated error term.
Estimated via spatialreg::errorsarlm(). Contains a spatial error
parameter lambda.
"durbin" (SDM)Extends the SAR model by including spatially lagged covariates (Durbin
terms). Estimated via spatialreg::lagsarlm() with Durbin = TRUE.
Contains both rho and lagged-covariate coefficients.
"sac" (SAC)Contains both a spatial lag of the outcome (rho) and a spatial error
term (lambda). Estimated via spatialreg::sacsarlm().
For models with a spatial lag (lag, durbin, sac), the total effect of
a covariate is decomposed into direct (own-unit), indirect (spillover),
and total effects using spatialreg::impacts() with R simulations for
inference. For the error model impacts equal OLS slopes and no
decomposition is meaningful; the $impacts element will be NULL.
After fitting, spdep::moran.test() is applied to the model residuals to
verify that spatial autocorrelation has been adequately absorbed. A
non-significant Moran p-value indicates a well-specified spatial model.
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer Academic Publishers.
LeSage, J., & Pace, R. K. (2009). Introduction to Spatial Econometrics. CRC Press / Taylor & Francis.
Bivand, R. S., Pebesma, E., & Gomez-Rubio, V. (2013). Applied Spatial Data Analysis with R (2nd ed.). Springer.
Elhorst, J. P. (2014). Spatial Econometrics: From Cross-Sectional Data to Panels. Springer.
sus_mod_spatial_weights(), sus_mod_spatial_moran(),
sus_mod_spatial_scan()
## Not run: library(climasus4r) # W <- sus_mod_spatial_weights(shp, style = "W") result <- sus_mod_spatial_reg( df = my_df, formula = deaths ~ mean_temp + precip + pib_pc, W = W, model = "lag", lang = "pt" ) print(result) summary(result) # SDM with spillovers result_sdm <- sus_mod_spatial_reg( df = my_df, formula = deaths ~ mean_temp + precip, W = W, model = "durbin" ) result_sdm$impacts ## End(Not run)## Not run: library(climasus4r) # W <- sus_mod_spatial_weights(shp, style = "W") result <- sus_mod_spatial_reg( df = my_df, formula = deaths ~ mean_temp + precip + pib_pc, W = W, model = "lag", lang = "pt" ) print(result) summary(result) # SDM with spillovers result_sdm <- sus_mod_spatial_reg( df = my_df, formula = deaths ~ mean_temp + precip, W = W, model = "durbin" ) result_sdm$impacts ## End(Not run)
Applies the Kulldorff circular spatial scan statistic to detect geographic
clusters of disease excess. The most-likely cluster and any significant
secondary clusters are identified by Monte Carlo hypothesis testing. The
analysis requires a tabular dataset with case counts and population
denominators at the municipality level, plus an sf polygon layer
providing municipality boundaries.
sus_mod_spatial_scan( df, cases, population, municipalities, expected = NULL, max_pop_frac = 0.5, n_simulations = 999L, alpha = 0.05, lang = c("pt", "en", "es"), verbose = TRUE )sus_mod_spatial_scan( df, cases, population, municipalities, expected = NULL, max_pop_frac = 0.5, n_simulations = 999L, alpha = 0.05, lang = c("pt", "en", "es"), verbose = TRUE )
df |
A |
cases |
Character. Name of the column in |
population |
Character. Name of the column in |
municipalities |
An |
expected |
Character or |
max_pop_frac |
Numeric in (0, 1]. Maximum fraction of the total
population that a single cluster window may contain. Default |
n_simulations |
Positive integer. Number of Monte Carlo simulations
for hypothesis testing. Default |
alpha |
Numeric in (0, 1). Significance level for secondary cluster
filtering. Default |
lang |
Character. Output language: |
verbose |
Logical. Print progress messages. Default |
A climasus_spatial_scan object (named list) with:
$most_likely_clusterNamed list:
location_ids (character vector of code_muni in the cluster),
observed (numeric), expected (numeric), RR (relative risk),
log_lik (log-likelihood ratio), p_value (Monte Carlo p-value).
$secondary_clustersList of lists with the same structure as
most_likely_cluster, one per significant secondary cluster. Empty
list when no secondary cluster is significant.
$n_clustersInteger. Total number of significant clusters
(1 + length of secondary_clusters), or 0 if the most-likely cluster
itself is not significant.
$dataTibble with one row per municipality: code_muni,
cases, population, expected, and a logical column in_mlc
indicating membership in the most-likely cluster.
$metaNamed list of analysis parameters.
$callThe matched call.
The scan statistic imposes circular windows of variable radius over the
map. For each window the likelihood ratio (LR) under a Poisson model
(observed vs. expected cases inside vs. outside the window) is computed.
The window with the maximum LR is the most-likely cluster. Its p-value is
obtained by comparing to the empirical distribution of max-LR under
n_simulations Monte Carlo permutations. Secondary clusters are non-
overlapping windows with LR > the alpha-level critical value from the
same Monte Carlo distribution.
Computations are delegated to SpatialEpi::kulldorff(). Municipality
centroids are derived from the polygon geometry using
sf::st_centroid() after reprojecting to WGS 84 (EPSG 4326) so that
longitude/latitude coordinates are passed to kulldorff().
Kulldorff, M. & Nagarwalla, N. (1995). Spatial disease clusters: detection and inference. Statistics in Medicine, 14(8), 799–810. doi:10.1002/sim.4780140809
Kulldorff, M. (1997). A spatial scan statistic. Communications in Statistics - Theory and Methods, 26(6), 1481–1496. doi:10.1080/03610929708831995
Kim, A. Y. & Wakefield, J. (2010). R data and methods for spatial epidemiology: the SpatialEpi package. University of Washington.
sus_spatial_join(), sus_mod_dlnm(), sus_mod_af()
## Not run: library(geobr) library(dplyr) # Download municipality polygons for Minas Gerais (state code 31) muni_sf <- geobr::read_municipality(code_muni = 31, year = 2020) muni_sf <- dplyr::rename(muni_sf, code_muni = code_muni) # Build a synthetic data.frame set.seed(42) df_cases <- tibble::tibble( code_muni = as.character(muni_sf$code_muni), cases = rpois(nrow(muni_sf), lambda = 5), population = sample(5000:200000, nrow(muni_sf), replace = TRUE) ) result <- sus_mod_spatial_scan( df = df_cases, cases = "cases", population = "population", municipalities = muni_sf, n_simulations = 199, lang = "pt" ) print(result) result$most_likely_cluster result$secondary_clusters ## End(Not run)## Not run: library(geobr) library(dplyr) # Download municipality polygons for Minas Gerais (state code 31) muni_sf <- geobr::read_municipality(code_muni = 31, year = 2020) muni_sf <- dplyr::rename(muni_sf, code_muni = code_muni) # Build a synthetic data.frame set.seed(42) df_cases <- tibble::tibble( code_muni = as.character(muni_sf$code_muni), cases = rpois(nrow(muni_sf), lambda = 5), population = sample(5000:200000, nrow(muni_sf), replace = TRUE) ) result <- sus_mod_spatial_scan( df = df_cases, cases = "cases", population = "population", municipalities = muni_sf, n_simulations = 199, lang = "pt" ) print(result) result$most_likely_cluster result$secondary_clusters ## End(Not run)
Constructs a spdep spatial weights object from an sf data frame of
municipality (or any polygon) boundaries. The result — a climasus_weights
object — is the required input for all other sus_mod_spatial_* functions
in the climasus4r pipeline.
sus_mod_spatial_weights( municipalities, style = "W", queen = TRUE, snap = NULL, zero_policy = TRUE, return_matrix = FALSE, lang = "pt", verbose = TRUE )sus_mod_spatial_weights( municipalities, style = "W", queen = TRUE, snap = NULL, zero_policy = TRUE, return_matrix = FALSE, lang = "pt", verbose = TRUE )
municipalities |
An |
style |
Character. Weight normalisation style passed to
|
queen |
Logical. If |
snap |
Numeric or |
zero_policy |
Logical. If |
return_matrix |
Logical. If |
lang |
Character. Language for CLI messages: |
verbose |
Logical. Print progress messages. Default |
Contiguity neighbours are detected with spdep::poly2nb(), which supports
both Queen (default, shared edge or vertex) and Rook (shared edge only)
contiguity. Municipalities that share no boundary ("spatial islands") are
automatically detected and reported. The resulting neighbour list is
normalised to a listw object via spdep::nb2listw().
A climasus_weights object (named list with class
c("climasus_weights", "list")) containing:
$listwspdep listw object ready for spatial modelling.
$nbspdep nb neighbour list (before weight normalisation).
$n_regionsInteger. Total number of regions / municipalities.
$n_islandsInteger. Number of regions with zero neighbours.
$island_idsCharacter or integer vector of island identifiers (empty if none).
$WDense numeric weight matrix, or NULL when
return_matrix = FALSE.
$styleCharacter. Weight normalisation style used.
$callThe matched call().
Municipal boundaries digitised at different scales often have small gaps or
overlaps at shared borders. The snap argument passes a distance tolerance
(in the units of the CRS) to spdep::poly2nb(): any two polygon boundaries
within snap distance are treated as touching. The default (NULL) uses
1e-3 (appropriate for degree-based CRS such as EPSG:4674 / SIRGAS2000).
For projected CRS (metres) consider values around 1 to 100.
"W" (default) — row-standardised: each neighbour weight = 1/n_neighbours
"B" — binary: 1 if neighbour, 0 otherwise
"C" — globally standardised
"U" — equal to "C" divided by number of neighbours
"S" — variance-stabilising (Tiefelsdorf et al. 1999)
"minmax" — min/max normalisation
Bivand, R. S., Pebesma, E., & Gomez-Rubio, V. (2013). Applied Spatial Data Analysis with R (2nd ed.). Springer.
Cliff, A. D., & Ord, J. K. (1981). Spatial Processes: Models and Applications. Pion.
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer Academic.
sus_mod_spatial_reg() for spatial lag model (SAR/SLM),
sus_mod_spatial_reg() for spatial error model (SEM),
sus_mod_spatial_bayes() for Bayesian hierarchical spatial models,
sus_mod_spatial_scan() for spatial scan statistics.
## Not run: library(geobr) library(climasus4r) # Download Nordeste municipalities (SIRGAS2000 / EPSG:4674) muni <- geobr::read_municipality(code_muni = "all", year = 2022) muni_ne <- muni[muni$abbrev_state %in% c("CE","RN","PB","PE","AL", "SE","BA","PI","MA"), ] # Row-standardised Queen contiguity (default) w <- sus_mod_spatial_weights(muni_ne) print(w) # Binary Rook weights, returning the dense W matrix w_rook <- sus_mod_spatial_weights( municipalities = muni_ne, style = "B", queen = FALSE, return_matrix = TRUE ) dim(w_rook$W) ## End(Not run)## Not run: library(geobr) library(climasus4r) # Download Nordeste municipalities (SIRGAS2000 / EPSG:4674) muni <- geobr::read_municipality(code_muni = "all", year = 2022) muni_ne <- muni[muni$abbrev_state %in% c("CE","RN","PB","PE","AL", "SE","BA","PI","MA"), ] # Row-standardised Queen contiguity (default) w <- sus_mod_spatial_weights(muni_ne) print(w) # Binary Rook weights, returning the dense W matrix w_rook <- sus_mod_spatial_weights( municipalities = muni_ne, style = "B", queen = FALSE, return_matrix = TRUE ) dim(w_rook$W) ## End(Not run)
Synthesizes pre-computed climasus model objects into a Strengths, Weaknesses, Opportunities, and Threats (SWOT) framework for climate-health risk communication and territorial planning. Each quadrant aggregates normalized indicators (0–100 scale) extracted from the supplied model objects; quadrant scores are returned both as continuous values and as user-defined categorical labels.
sus_mod_swot( vulnerability = NULL, af = NULL, burden = NULL, dlnm = NULL, sensitivity = NULL, score_type = c("both", "numeric", "categorical"), breaks = c(33, 66), labels = NULL, city_col = "city", lang = c("pt", "en", "es"), verbose = TRUE )sus_mod_swot( vulnerability = NULL, af = NULL, burden = NULL, dlnm = NULL, sensitivity = NULL, score_type = c("both", "numeric", "categorical"), breaks = c(33, 66), labels = NULL, city_col = "city", lang = c("pt", "en", "es"), verbose = TRUE )
vulnerability |
A |
af |
A |
burden |
A |
dlnm |
A |
sensitivity |
A |
score_type |
Character. Which score types to compute:
|
breaks |
Numeric vector. Strictly increasing cut-points in (0, 100)
used to convert numeric scores into categories. Default |
labels |
Character vector or |
city_col |
Character. Column name of the city/entity identifier in the
|
lang |
Character. Language for labels: |
verbose |
Logical. Print progress messages. Default |
A climasus_swot list with:
$scoresTibble. One row per entity with: entity,
S_score, W_score, O_score, T_score (numeric 0–100, NA
when no indicators are available for a quadrant), n_S, n_W,
n_O, n_T (indicator counts). When score_type
c("categorical","both"): S_cat, W_cat, O_cat, T_cat.
$indicatorsTibble (long). One row per
(entity quadrant indicator): entity,
quadrant, ind_code, indicator, raw_value, norm_score,
direction ("positive" or "negative").
$metaList: n_entities, n_indicators, inputs_used,
score_type, breaks, labels, lang, call_time.
| Quadrant | Meaning | Indicators from each input |
| S Strengths | Current protective factors | adaptive_capacity_score (VI), low total AF% (af/burden), low burden rank |
| W Weaknesses | Current vulnerabilities | sensitivity_score (VI), heat/cold AF% (af), stratum RR inequality (sensitivity) |
| O Opportunities | Intervention windows | Low VI percentile (VI), low current exposure (VI) |
| T Threats | Climate-health risks | exposure_score + vi_score (VI), heat RR at P95 (dlnm), attributable number (burden), max stratum RR (sensitivity)
|
All indicators are normalized to 0–100 within the supplied data. For Strength and Opportunity indicators the raw value is already oriented so that higher = better; for Weakness and Threat indicators, higher means worse. The quadrant score is the mean of available indicator scores.
When vulnerability and/or burden provide multi-city data, the SWOT is
computed per city. Single-city inputs (af, dlnm, sensitivity) are
broadcast to all detected entities and treated as shared context.
sus_mod_plot_swot(), sus_mod_vulnerability_index(),
sus_mod_af(), sus_mod_burden(), sus_mod_dlnm(),
sus_mod_sensitivity()
## Not run: swot <- sus_mod_swot( vulnerability = vi_result, af = af_result, burden = burden_result, dlnm = dlnm_result, score_type = "both", lang = "pt" ) swot$scores sus_mod_plot_swot(swot, type = "matrix", lang = "pt") sus_mod_plot_swot(swot, type = "radar", lang = "en") ## End(Not run)## Not run: swot <- sus_mod_swot( vulnerability = vi_result, af = af_result, burden = burden_result, dlnm = dlnm_result, score_type = "both", lang = "pt" ) swot$scores sus_mod_plot_swot(swot, type = "matrix", lang = "pt") sus_mod_plot_swot(swot, type = "radar", lang = "en") ## End(Not run)
Builds a city-level composite vulnerability index following the IPCC AR6 vulnerability framework: Vulnerability = f(Exposure + Sensitivity - Adaptive Capacity). Each pillar is constructed from a user-supplied data frame of city-level numeric indicators. Indicators are normalized (min-max or z-score), weighted within pillars, and combined into a final score ∈ [0, 1] where 1 = most vulnerable.
sus_mod_vulnerability_index( exposure_df = NULL, sensitivity_df = NULL, adaptive_capacity_df = NULL, fits = NULL, city_col = "city", normalize = "minmax", weights = NULL, pillar_weights = c(exposure = 1, sensitivity = 1, adaptive_capacity = 1), hot_percentile = 0.99, cold_percentile = 0.01, lang = "pt", verbose = TRUE )sus_mod_vulnerability_index( exposure_df = NULL, sensitivity_df = NULL, adaptive_capacity_df = NULL, fits = NULL, city_col = "city", normalize = "minmax", weights = NULL, pillar_weights = c(exposure = 1, sensitivity = 1, adaptive_capacity = 1), hot_percentile = 0.99, cold_percentile = 0.01, lang = "pt", verbose = TRUE )
exposure_df |
A data frame with one row per city and numeric columns
representing exposure indicators (higher value = more hazard).
Typically derived by summarising a |
sensitivity_df |
A data frame with numeric sensitivity indicators
(higher value = more sensitive population). Can include demographic
columns (% elderly, % children), health-outcome rates, or any other
stratum-level vulnerability marker. If |
adaptive_capacity_df |
A data frame with numeric adaptive capacity
indicators (higher value = more adaptive capacity = less vulnerable).
This pillar is inverted internally before computing VI. Typical columns
come from |
fits |
Optional named list of |
city_col |
Character. Name of the city identifier column present in
every supplied data frame. Default |
normalize |
Character. Normalization method: |
weights |
Named numeric vector. Within-pillar indicator weights. Names
must match indicator column names in the respective data frame. Indicators
not listed receive weight 1. Weights are normalized to sum to 1 within
each pillar. Example: |
pillar_weights |
Named numeric vector with elements |
hot_percentile |
Numeric in (0, 1). Quantile used as the "hot"
threshold for DLNM extraction. Default |
cold_percentile |
Numeric in (0, 1). Quantile used as the "cold"
threshold for DLNM extraction. Default |
lang |
Character. Language for messages: |
verbose |
Logical. Print progress messages. Default |
Exposure quantifies how much climate hazard a city experiences (e.g.,
mean maximum temperature, number of heat-wave days, threshold exceedances
from sus_climate_aggregate()). Sensitivity captures how responsive
local health outcomes are to the hazard (e.g., percentage elderly,
chronic-disease rates, DLNM-derived cumulative RRs from sus_mod_dlnm()).
Adaptive Capacity reflects ability to cope (e.g., HDI, piped-water
coverage, healthcare density from sus_census_join() or
sus_spatial_join()). Providing fits — a named list of climasus_dlnm
objects — automatically extracts heat and cold RRs plus a sensitivity index
and merges them into the sensitivity pillar.
A climasus_vi object (named list) with:
$vi_tableTibble sorted by vi_rank (1 = most vulnerable).
Columns: city identifier, vi_score ∈ [0, 1], exposure_score,
sensitivity_score, adaptive_capacity_score (raw, before
inversion), vi_rank (integer), vi_percentile (0–100, higher =
more vulnerable relative to peers).
$pillar_scoresLong-format tibble with columns city identifier,
pillar ("exposure", "sensitivity", "adaptive_capacity"),
and score (raw pillar score before AC inversion).
$normalized_indicatorsWide tibble: city identifier + all
normalized indicator values, prefixed by pillar (exp_*, sen_*,
ac_*).
$raw_indicatorsWide tibble: city identifier + all original (un-normalized) indicator values, prefixed by pillar.
$weightsNamed list with within-pillar normalized weights for
exposure, sensitivity, and adaptive_capacity, plus the
normalized pillar weights vector.
$gini_coefficientGini coefficient of the VI distribution across cities (0 = perfect equality, 1 = all burden on one city).
$metaNamed list of all parameters used in this call.
Each indicator column is normalized to
∈ [0, 1] (min-max) or (z-score). The pillar score
for city is the within-pillar weighted mean of its normalized
indicators. The adaptive-capacity pillar is inverted before combining
(higher capacity ↔ lower vulnerability):
Missing pillar scores for a city are omitted and remaining weights re-normalized, so partial data does not force full exclusion.
IPCC (2022). Sixth Assessment Report — Working Group II. Chapter 16: Key Risks across Sectors and Regions. Cambridge University Press.
Turner, B.L., et al. (2003). A framework for vulnerability analysis in sustainability science. PNAS, 100(14), 8074–8079. doi:10.1073/pnas.1231335100
Cutter, S.L., et al. (2003). Social vulnerability to environmental hazards. Social Science & Medicine, 56(11), 2301–2322. doi:10.1016/S0277-9536(02)00605-X
sus_mod_sensitivity(), sus_mod_dlnm(), sus_mod_burden(),
sus_census_join(), sus_climate_aggregate()
## Not run: # ── Minimal example with two pillars ───────────────────────────────────── exposure_df <- data.frame( city = c("fortaleza", "recife", "salvador"), mean_tmax = c(32.1, 30.5, 31.2), heat_wave_days = c(45, 30, 38) ) adaptive_capacity_df <- data.frame( city = c("fortaleza", "recife", "salvador"), hdi = c(0.754, 0.772, 0.759), pct_piped_water = c(72.1, 68.4, 74.3) ) vi <- sus_mod_vulnerability_index( exposure_df = exposure_df, adaptive_capacity_df = adaptive_capacity_df, lang = "pt" ) print(vi) tidy(vi) # ── Full 3-pillar with DLNM auto-extraction ─────────────────────────────── dlnm_fits <- list( fortaleza = sus_mod_dlnm(df_fortaleza, ...), recife = sus_mod_dlnm(df_recife, ...) ) vi_full <- sus_mod_vulnerability_index( exposure_df = exposure_df, fits = dlnm_fits, # auto-extracted to sensitivity adaptive_capacity_df = adaptive_capacity_df, weights = c(mean_tmax = 2), # double-weight temperature pillar_weights = c(exposure = 1.5, sensitivity = 1, adaptive_capacity = 1), lang = "en" ) ## End(Not run)## Not run: # ── Minimal example with two pillars ───────────────────────────────────── exposure_df <- data.frame( city = c("fortaleza", "recife", "salvador"), mean_tmax = c(32.1, 30.5, 31.2), heat_wave_days = c(45, 30, 38) ) adaptive_capacity_df <- data.frame( city = c("fortaleza", "recife", "salvador"), hdi = c(0.754, 0.772, 0.759), pct_piped_water = c(72.1, 68.4, 74.3) ) vi <- sus_mod_vulnerability_index( exposure_df = exposure_df, adaptive_capacity_df = adaptive_capacity_df, lang = "pt" ) print(vi) tidy(vi) # ── Full 3-pillar with DLNM auto-extraction ─────────────────────────────── dlnm_fits <- list( fortaleza = sus_mod_dlnm(df_fortaleza, ...), recife = sus_mod_dlnm(df_recife, ...) ) vi_full <- sus_mod_vulnerability_index( exposure_df = exposure_df, fits = dlnm_fits, # auto-extracted to sensitivity adaptive_capacity_df = adaptive_capacity_df, weights = c(mean_tmax = 2), # double-weight temperature pillar_weights = c(exposure = 1.5, sensitivity = 1, adaptive_capacity = 1), lang = "en" ) ## End(Not run)
Converts a climasus4r pipeline expression into a portable, self-contained
artefact - an R script (.R), RMarkdown document (.Rmd), Quarto document
(.qmd), or an encapsulated R function - suitable for sharing, archiving,
and re-execution. The exported file embeds session metadata (R version,
package versions, timestamp, platform), an editable parameters block, and
optional validation checks, following Reproducible Analytical Pipeline
principles.
sus_rap_export( pipeline = NULL, file_path = NULL, format = c("script", "rmarkdown", "quarto", "function"), include_metadata = TRUE, include_validation = TRUE, include_documentation = c("standard", "minimal", "comprehensive"), output_type = c("analysis", "dashboard", "report"), lang = "pt", overwrite = FALSE )sus_rap_export( pipeline = NULL, file_path = NULL, format = c("script", "rmarkdown", "quarto", "function"), include_metadata = TRUE, include_validation = TRUE, include_documentation = c("standard", "minimal", "comprehensive"), output_type = c("analysis", "dashboard", "report"), lang = "pt", overwrite = FALSE )
pipeline |
A pipeline expression (created with |
file_path |
|
format |
|
include_metadata |
|
include_validation |
|
include_documentation |
|
output_type |
|
lang |
|
overwrite |
|
Invisibly, a character vector with the exported file content.
Side-effect: writes to file_path when provided.
"script"Standalone .R script with header, params block,
pipeline execution, validation, and sessionInfo().
"rmarkdown".Rmd document with YAML params, setup chunk,
pipeline, validation, and optional visualisation section.
"quarto".qmd document using Quarto YAML front matter.
"function"Parametrised .R function with Roxygen2 header.
## Not run: pipeline <- quote( sus_data_import(uf = "SP", years = 2020:2022, system = "SIM-DO") |> sus_data_clean_encoding() |> sus_data_filter_cid(cid_group = "respiratory") |> sus_data_aggregate(by = "month") ) # Export as R script sus_rap_export(pipeline, "pipeline_respiratorio.R", lang = "pt") # Export as Quarto document sus_rap_export(pipeline, "analise.qmd", format = "quarto", include_documentation = "comprehensive") ## End(Not run)## Not run: pipeline <- quote( sus_data_import(uf = "SP", years = 2020:2022, system = "SIM-DO") |> sus_data_clean_encoding() |> sus_data_filter_cid(cid_group = "respiratory") |> sus_data_aggregate(by = "month") ) # Export as R script sus_rap_export(pipeline, "pipeline_respiratorio.R", lang = "pt") # Export as Quarto document sus_rap_export(pipeline, "analise.qmd", format = "quarto", include_documentation = "comprehensive") ## End(Not run)
Reads a YAML recipe exported by sus_rap_recipe() and reconstructs a
rap_object. Parameter overrides can be supplied at import time. Passing
execute = TRUE immediately re-runs the pipeline using sus_rap_run().
sus_rap_from_recipe( recipe_path, override_params = list(), execute = FALSE, lang = "pt", ... )sus_rap_from_recipe( recipe_path, override_params = list(), execute = FALSE, lang = "pt", ... )
recipe_path |
|
override_params |
Named list of parameters to override from the recipe
(e.g. |
execute |
|
lang |
|
... |
Additional arguments forwarded to |
A rap_object (or the pipeline result when execute = TRUE).
## Not run: rap <- sus_rap_from_recipe("pipeline_sp.yaml") print(rap) # Import with parameter overrides rap_rj <- sus_rap_from_recipe("pipeline_sp.yaml", override_params = list(uf = "RJ")) ## End(Not run)## Not run: rap <- sus_rap_from_recipe("pipeline_sp.yaml") print(rap) # Import with parameter overrides rap_rj <- sus_rap_from_recipe("pipeline_sp.yaml", override_params = list(uf = "RJ")) ## End(Not run)
Opens a Shiny application that lets users visually configure pipeline parameters (UF, years, system, aggregation), preview the generated code, and execute or export the RAP - all without writing R code directly.
sus_rap_gui(rap = NULL, launch.browser = TRUE, ...)sus_rap_gui(rap = NULL, launch.browser = TRUE, ...)
rap |
A |
launch.browser |
|
... |
Additional arguments forwarded to |
Does not return; runs the Shiny application interactively.
Parameter editors: UF checkboxes, year range slider, system dropdown, aggregation unit selector, language selector.
Step-by-step pipeline card view showing each function and its arguments.
Live log console. Buttons: Preview, Run, Export, Save Recipe.
## Not run: sus_rap_gui() rap <- sus_rap_read("pipeline_sp.R") sus_rap_gui(rap) ## End(Not run)## Not run: sus_rap_gui() rap <- sus_rap_read("pipeline_sp.R") sus_rap_gui(rap) ## End(Not run)
Prints a structured summary of a rap_object. When two objects are
supplied, performs a side-by-side diff showing changed parameters, added or
removed pipeline steps, and package version drift.
sus_rap_inspect(rap, rap2 = NULL, verbose = TRUE, lang = "pt")sus_rap_inspect(rap, rap2 = NULL, verbose = TRUE, lang = "pt")
rap |
A |
rap2 |
A second |
verbose |
|
lang |
|
Invisibly, a list with $summary (and $diff when rap2 is given).
## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_inspect(rap) rap_v2 <- sus_rap_read("pipeline_sp_v2.R") sus_rap_inspect(rap, rap_v2) ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_inspect(rap) rap_v2 <- sus_rap_read("pipeline_sp_v2.R") sus_rap_inspect(rap, rap_v2) ## End(Not run)
Runs a _targets.R pipeline (generated by sus_rap_targets()) using
targets::tar_make(), with optional parallelism via workers.
sus_rap_make( rap, workers = 1L, reporter = "verbose", branching = "none", lang = "pt", ... )sus_rap_make( rap, workers = 1L, reporter = "verbose", branching = "none", lang = "pt", ... )
rap |
A |
workers |
|
reporter |
|
branching |
|
lang |
|
... |
Additional arguments forwarded to |
A list with $results, $rap, and $store.
## Not run: rap <- sus_rap_read("pipeline_sp.R") result <- sus_rap_make(rap, workers = 2, branching = "uf") head(result$results) ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") result <- sus_rap_make(rap, workers = 2, branching = "uf") head(result$results) ## End(Not run)
Reads a file produced by sus_rap_export() and reconstructs a live
rap_object containing session metadata, configurable parameters, and the
pipeline step list. The result can be inspected with sus_rap_inspect(),
re-executed with sus_rap_run(), or patched with sus_rap_update().
sus_rap_read(file_path, lang = "pt", validate = TRUE)sus_rap_read(file_path, lang = "pt", validate = TRUE)
file_path |
|
lang |
|
validate |
|
A rap_object list with fields $metadata, $params, $steps,
$structure, $source, $format, and $raw.
## Not run: rap <- sus_rap_read("pipeline_sp.R") print(rap) ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") print(rap) ## End(Not run)
Serialises the essential information of a rap_object - parameters,
pipeline steps, and package versions - into a compact YAML file (typically
under 50 lines). The recipe can be shared with colleagues and re-imported
with sus_rap_from_recipe().
sus_rap_recipe( rap, file_path = NULL, include_data_hash = TRUE, lang = "pt", overwrite = FALSE )sus_rap_recipe( rap, file_path = NULL, include_data_hash = TRUE, lang = "pt", overwrite = FALSE )
rap |
A |
file_path |
|
include_data_hash |
|
lang |
|
overwrite |
|
Invisibly, the path of the created .yaml file.
## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_recipe(rap, "pipeline_sp.yaml") ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_recipe(rap, "pipeline_sp.yaml") ## End(Not run)
Reconstructs and executes the pipeline contained in a rap_object. Any
parameters passed via ... override the originals before execution, making
it easy to replay an analysis for a different state or year range.
sus_rap_run(rap, ..., envir = parent.frame(), dry_run = FALSE, lang = "pt")sus_rap_run(rap, ..., envir = parent.frame(), dry_run = FALSE, lang = "pt")
rap |
A |
... |
Name-value pairs overriding fields in |
envir |
|
dry_run |
|
lang |
|
Invisibly, the data.frame produced by the pipeline.
## Not run: rap <- sus_rap_read("pipeline_sp.R") df <- sus_rap_run(rap, uf = "RJ", years = 2021:2023) sus_rap_run(rap, dry_run = TRUE) ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") df <- sus_rap_run(rap, uf = "RJ", years = 2021:2023) sus_rap_run(rap, dry_run = TRUE) ## End(Not run)
Converts a rap_object or a pipeline expression into a ready-to-use
_targets.R file. The generated script uses targets::tar_target() with
optional dynamic branching over UFs, years, or their Cartesian product.
sus_rap_targets( pipeline, file_path = "_targets.R", branching = c("none", "uf", "year", "cross"), workers = 1L, include_qc = TRUE, lang = "pt", overwrite = FALSE )sus_rap_targets( pipeline, file_path = "_targets.R", branching = c("none", "uf", "year", "cross"), workers = 1L, include_qc = TRUE, lang = "pt", overwrite = FALSE )
pipeline |
A |
file_path |
|
branching |
|
workers |
|
include_qc |
|
lang |
|
overwrite |
|
Invisibly, the path of the generated _targets.R file.
"none"Single analysis, no branching.
"uf"One branch per UF - ideal for multi-state comparisons.
"year"One branch per year.
"cross"All UF-year combinations via tidyr::crossing().
## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_targets(rap, "_targets.R", branching = "uf", workers = 4) # then run: targets::tar_make() ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") sus_rap_targets(rap, "_targets.R", branching = "uf", workers = 4) # then run: targets::tar_make() ## End(Not run)
Creates a ready-to-use project directory with a _targets.R pipeline,
a parameterised Quarto report, optional renv dependency snapshot,
optional GitHub Actions CI workflow, and a structured file layout
following RAP best practices.
sus_rap_template( path, name, system = "SIM-DO", include_renv = TRUE, include_targets = TRUE, include_quarto = TRUE, include_github_actions = FALSE, lang = "pt" )sus_rap_template( path, name, system = "SIM-DO", include_renv = TRUE, include_targets = TRUE, include_quarto = TRUE, include_github_actions = FALSE, lang = "pt" )
path |
|
name |
|
system |
|
include_renv |
|
include_targets |
|
include_quarto |
|
include_github_actions |
|
lang |
|
Invisibly, the absolute path of the created project directory.
<name>/ |-- _targets.R # targets pipeline |-- run.R # convenience runner: source + tar_make() |-- analysis.qmd # parameterised Quarto report |-- R/ | `-- functions.R # custom analysis functions |-- data/ # raw data (git-ignored) |-- output/ # results (git-ignored) |-- renv/ # renv library (when include_renv = TRUE) |-- renv.lock |-- .gitignore `-- README.md
## Not run: sus_rap_template( path = "~/projetos", name = "dengue_am", system = "SINAN", lang = "pt" ) ## End(Not run)## Not run: sus_rap_template( path = "~/projetos", name = "dengue_am", system = "SINAN", lang = "pt" ) ## End(Not run)
Applies targeted patches to the editable params <- list(...) block of an
exported RAP file without re-exporting from scratch. A .bak backup is
created before any modification.
sus_rap_update(rap, ..., backup = TRUE, lang = "pt")sus_rap_update(rap, ..., backup = TRUE, lang = "pt")
rap |
A |
... |
Named parameters to update (e.g. |
backup |
|
lang |
|
Invisibly, the updated rap_object (re-read from the patched file).
## Not run: rap <- sus_rap_read("pipeline_sp.R") rap_rj <- sus_rap_update(rap, uf = '"RJ"', years = "2021:2024") ## End(Not run)## Not run: rap <- sus_rap_read("pipeline_sp.R") rap_rj <- sus_rap_update(rap, uf = '"RJ"', years = "2021:2024") ## End(Not run)
Computes a set of standardised indicators from the columns already present
in a climasus_df object (typically the output of sus_census_join()).
Indicators span demographics, socioeconomic vulnerability, mortality,
morbidity, maternal-child health, and health-resource availability.
Column names from the census aggregation step (e.g. V003_sum) can be
mapped to the formula-space names expected by each indicator via
col_mapping.
sus_socio_compute_indicators( df, indicators = NULL, col_mapping = list(), confidence_level = 0.95, add_ci = TRUE, lang = "pt", verbose = TRUE )sus_socio_compute_indicators( df, indicators = NULL, col_mapping = list(), confidence_level = 0.95, add_ci = TRUE, lang = "pt", verbose = TRUE )
df |
A |
indicators |
Character vector of indicator IDs to compute. If |
col_mapping |
Named list mapping formula-space variable names to actual
column names in list(pop_young = "pop_0_14_sum", total_hh = "V003_sum") Only mappings that override the defaults need to be specified. |
confidence_level |
Numeric. Confidence level for Poisson / Binomial
intervals. Default |
add_ci |
Logical. If |
lang |
Language for messages: |
verbose |
Logical. Print progress messages. Default |
Formula evaluation: each indicator formula is evaluated using
rlang::eval_tidy() against a named-list environment built from the
resolved column values, so no package-level NSE column names are needed.
Missing columns: if a requested indicator lacks required columns (after
applying col_mapping), a warning is emitted and the indicator is skipped.
The function never aborts due to missing columns.
Confidence intervals:
Poisson (Garwood exact): for event-count / population-at-risk rates (mortality, incidence, hospitalisation).
Binomial (Wilson score): for proportions (%, coverage indices).
None: for ratios with complex numerators or direct index values.
The input climasus_df with additional columns prefixed ind_:
ind_<id> — computed value
ind_<id>_low / ind_<id>_high — confidence-interval bounds
(only for Poisson/Binomial indicators when add_ci = TRUE)
sus_meta is updated to type = "indicators" with a history entry.
sus_census_join(), sus_socio_list_indicators()
## Not run: df_ind <- sus_socio_compute_indicators( df_census, indicators = c("dependency_ratio", "water_connection_rate"), col_mapping = list( pop_young = "pop_0_14_sum", pop_elderly = "pop_65_plus_sum", pop_working = "pop_15_64_sum", hh_water = "V111_sum", total_hh = "V003_sum" ) ) ## End(Not run)## Not run: df_ind <- sus_socio_compute_indicators( df_census, indicators = c("dependency_ratio", "water_connection_rate"), col_mapping = list( pop_young = "pop_0_14_sum", pop_elderly = "pop_65_plus_sum", pop_working = "pop_15_64_sum", hh_water = "V111_sum", total_hh = "V003_sum" ) ) ## End(Not run)
Returns a data frame describing all indicators available in
sus_socio_compute_indicators(), including their IDs, names,
categories, required columns, and uncertainty method.
sus_socio_list_indicators(lang = "pt", category = NULL)sus_socio_list_indicators(lang = "pt", category = NULL)
lang |
Language for indicator names: |
category |
Optional character vector to filter by category. Use |
A tibble with columns id, name, category, required_cols,
unit, uncertainty_method, source.
sus_socio_list_indicators(lang = "pt") sus_socio_list_indicators(lang = "en", category = "mortality")sus_socio_list_indicators(lang = "pt") sus_socio_list_indicators(lang = "en", category = "mortality")
Performs a spatial join between a data.frame containing SUS data and official Brazilian geographic boundaries (state, municipality, census tract) or geocodes postal codes (CEP). This function is the core spatial engine for the entire climasus4r package and serves as the foundation for all spatial analyses.
sus_spatial_join( df, level = "munic", join_col = NULL, lang = "pt", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", verbose = TRUE )sus_spatial_join( df, level = "munic", join_col = NULL, lang = "pt", use_cache = TRUE, cache_dir = "~/.climasus4r_cache/spatial", verbose = TRUE )
df |
A |
level |
Character string specifying the geographic aggregation level. Default is
Note: |
join_col |
Character string with the name of the column in |
lang |
Character string specifying the language for messages.
Options: |
use_cache |
Logical. If |
cache_dir |
Character string specifying the directory to store cached files.
Default is |
verbose |
Logical. If |
Caching Strategy:
Spatial data is cached as Parquet files in ~/.climasus4r_cache/spatial to:
Avoid repeated downloads
Improve performance (10-100x faster)
Enable offline reuse
Code Normalization:
Municipality codes: Accepts 6 or 7 digits; 7-digit codes have the verification digit removed automatically
CEP: Always zero-padded to 8 characters
All join columns are coerced to character type
An sf object (Simple Features data.frame) with all original columns from
df plus a geometry column containing the spatial geometries:
/munic/neighborhood: POLYGON or MULTIPOLYGON geometries
/cnes/cep: POINT geometries (geocoded locations)
Pereira, R.H.M.; Goncalves, C.N.; et. all (2019) geobr: Loads Shapefiles of Official Spatial Data Sets of Brazil. GitHub repository - https://github.com/ipeaGIT/geobr. Pereira, Rafael H. M.; Barbosa, Rogerio J. (2023) censobr: Download Data from Brazil's Population Census. R package version v0.4.0, https://CRAN.R-project.org/package=censobr. DOI: 10.32614/CRAN.package.censobr.
## Not run: library(climasus4r) # Example 1: Link mortality data to municipalities df_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize(lang = "pt") sf_sim <- sus_spatial_join( df = df_sim, level = "munic", lang = "pt" ) # Example 3: Geocode CEP for hospitalization data (SIH only) df_sih <- sus_data_import(uf = "RJ", year = 2023, system = "SIH-RD") %>% sus_data_standardize(lang = "pt") sf_cep <- sus_spatial_join( df = df_sih, level = "cep", lang = "pt" ) # Example 4: Census tract level analysis sf_census <- sus_spatial_join( df = df_sim, level = "schools", lang = "pt" ) ## End(Not run)## Not run: library(climasus4r) # Example 1: Link mortality data to municipalities df_sim <- sus_data_import(uf = "SP", year = 2023, system = "SIM-DO") %>% sus_data_standardize(lang = "pt") sf_sim <- sus_spatial_join( df = df_sim, level = "munic", lang = "pt" ) # Example 3: Geocode CEP for hospitalization data (SIH only) df_sih <- sus_data_import(uf = "RJ", year = 2023, system = "SIH-RD") %>% sus_data_standardize(lang = "pt") sf_cep <- sus_spatial_join( df = df_sih, level = "cep", lang = "pt" ) # Example 4: Census tract level analysis sf_census <- sus_spatial_join( df = df_sim, level = "schools", lang = "pt" ) ## End(Not run)
Prints a colour-coded pipeline overview to the console and, optionally, opens a self-contained HTML page in the browser (or RStudio viewer) showing all ten stages of the climasus4r health-climate-environment workflow plus utility functions.
sus_welcome(lang = "pt", output = c("console", "html"), open = TRUE)sus_welcome(lang = "pt", output = c("console", "html"), open = TRUE)
lang |
Character. Language: |
output |
Character vector. Outputs to produce: |
open |
Logical. If |
Invisibly returns the path to the HTML file (or NULL when
"html" is not in output). Called for its side effects.
## Not run: sus_welcome() sus_welcome(lang = "en") sus_welcome(output = "html", open = TRUE) sus_welcome(lang = "es", output = c("console", "html")) ## End(Not run)## Not run: sus_welcome() sus_welcome(lang = "en") sus_welcome(output = "html", open = TRUE) sus_welcome(lang = "es", output = c("console", "html")) ## End(Not run)
Returns a single-row tibble suitable for dplyr::bind_rows() pooling
across multiple cities or time periods.
## S3 method for class 'climasus_af' tidy(x, ...)## S3 method for class 'climasus_af' tidy(x, ...)
x |
A |
... |
Unused. |
A one-row tibble with key attributable fraction statistics.
Returns the full ranked burden table with the cumulative concentration
percentage joined. Each row is one city (one row per component when
component = "all" was used). Suitable for dplyr::bind_rows() across
multiple analyses or for plotting.
## S3 method for class 'climasus_burden' tidy(x, ...)## S3 method for class 'climasus_burden' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with all burden-table columns plus cumulative_pct.
Returns the OR table as a tibble, with analysis metadata columns prepended.
Suitable for row-binding across multiple analyses with dplyr::bind_rows().
## S3 method for class 'climasus_casecrossover' tidy(x, ...)## S3 method for class 'climasus_casecrossover' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with one row per exposure term.
Convenience extractor compatible with dplyr::bind_rows() for pooling
results across multiple model runs.
## S3 method for class 'climasus_dlnm' tidy(x, ...)## S3 method for class 'climasus_dlnm' tidy(x, ...)
x |
A |
... |
Unused. |
A one-row tibble with key model statistics.
Returns a one-row tibble summarising the excess result, suitable for
combining across multiple analyses with dplyr::bind_rows().
## S3 method for class 'climasus_excess' tidy(x, ...)## S3 method for class 'climasus_excess' tidy(x, ...)
x |
A |
... |
Unused. |
A one-row tibble.
Returns the effects table with analysis metadata columns prepended.
Suitable for combining results across series with dplyr::bind_rows().
## S3 method for class 'climasus_its' tidy(x, ...)## S3 method for class 'climasus_its' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with one row per interruption.
Returns a one-row tibble summarising the meta-regression result plus
a covariate_tests column containing the nested covariate test table.
Suitable for combining results across multiple analyses.
## S3 method for class 'climasus_metaregression' tidy(x, ...)## S3 method for class 'climasus_metaregression' tidy(x, ...)
x |
A |
... |
Unused. |
A one-row tibble.
Returns the predictions table with observed, fitted, cv_predicted,
and residual columns. Suitable for plotting, residual diagnostics,
or combining across analyses.
## S3 method for class 'climasus_ml' tidy(x, ...)## S3 method for class 'climasus_ml' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with one row per observation.
Returns a one-row tibble summarising the pooled result, suitable for
combining across multiple pooling runs with dplyr::bind_rows().
## S3 method for class 'climasus_pool' tidy(x, ...)## S3 method for class 'climasus_pool' tidy(x, ...)
x |
A |
... |
Unused. |
A one-row tibble.
Returns the comparison table with metadata columns prepended, suitable for
combining results across analyses with dplyr::bind_rows().
## S3 method for class 'climasus_sensitivity' tidy(x, ...)## S3 method for class 'climasus_sensitivity' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with one row per stratum.
Tidy a climasus_swot object into a flat scores tibble
## S3 method for class 'climasus_swot' tidy(x, ...)## S3 method for class 'climasus_swot' tidy(x, ...)
x |
A |
... |
Ignored. |
A tibble with one row per entity.
Returns the full VI table with normalized indicator columns appended, one row per city. Suitable for plotting, further modelling, or export.
## S3 method for class 'climasus_vi' tidy(x, ...)## S3 method for class 'climasus_vi' tidy(x, ...)
x |
A |
... |
Unused. |
A tibble with city-level VI scores, pillar scores, indicator-level normalized values, and raw values — all in wide format.
Extract variance-covariance from a climasus_metaregression object
## S3 method for class 'climasus_metaregression' vcov(object, ...)## S3 method for class 'climasus_metaregression' vcov(object, ...)
object |
A |
... |
Passed to |
Variance-covariance matrix of meta-regression coefficients.
Extract pooled variance-covariance from a climasus_pool object
## S3 method for class 'climasus_pool' vcov(object, ...)## S3 method for class 'climasus_pool' vcov(object, ...)
object |
A |
... |
Passed to |
Pooled variance-covariance matrix.
Convenience wrapper that opens a persistent DuckDB connection to
path, registers the data and metadata, then closes the connection.
write_duckdb_climasus(x, path, view_name = "climasus_data", overwrite = TRUE)write_duckdb_climasus(x, path, view_name = "climasus_data", overwrite = TRUE)
x |
A |
path |
Character. File path for the DuckDB database (e.g.
|
view_name |
Character. Name of the table inside the DuckDB file
(default: |
overwrite |
Logical. Whether to overwrite an existing table (default:
|
invisible(x) — the original climasus_df, updated
with backend = "duckdb" in its metadata.
## Not run: df <- write_duckdb_climasus(df, "data/sim_respiratory.duckdb") sus_meta(df, "backend") # "duckdb" # Read back later con <- duckdb::dbConnect(duckdb::duckdb(), "data/sim_respiratory.duckdb") df2 <- from_duckdb_climasus(con, "climasus_data") duckdb::dbDisconnect(con) ## End(Not run)## Not run: df <- write_duckdb_climasus(df, "data/sim_respiratory.duckdb") sus_meta(df, "backend") # "duckdb" # Read back later con <- duckdb::dbConnect(duckdb::duckdb(), "data/sim_respiratory.duckdb") df2 <- from_duckdb_climasus(con, "climasus_data") duckdb::dbDisconnect(con) ## End(Not run)
Convenience wrapper around as_arrow_climasus() and
arrow::write_parquet(). Metadata is preserved in the Parquet
file's schema.
write_parquet_climasus(x, path, ...)write_parquet_climasus(x, path, ...)
x |
A |
path |
Character. File path for the Parquet file (e.g.
|
... |
Additional arguments passed to |
invisible(x) — the original climasus_df, updated
with backend = "parquet" in its metadata.
## Not run: df <- write_parquet_climasus(df, "data/sim_respiratory.parquet") sus_meta(df, "backend") # "parquet" ## End(Not run)## Not run: df <- write_parquet_climasus(df, "data/sim_respiratory.parquet") sus_meta(df, "backend") # "parquet" ## End(Not run)