Skip to contents

Introduction

Introductory Tutorial — This tutorial provides a practical guide to getting started with the climasus4r package. The goal is to demonstrate the basic workflow, from installing the package to building time series from DATASUS health data, integrating health, climate, and environmental information.

Brazil’s Unified Health System (SUS) makes large public databases available, such as SIM, SIH, SINAN, CNES, and SINASC. However, these data usually require import, cleaning, standardization, and aggregation steps before they can be used in epidemiological analyses.

The climasus4r package was developed to automate and standardize this process, enabling reproducible, fast, and scalable analyses in climate, environment, and public health studies.

🎯 What you will learn

📦

Installation

Install the climasus4r package quickly and efficiently

⚡

Optimized Import

Import DATASUS data with caching and parallel processing

🧹

Cleaning and Standardization

Fix encoding issues and standardize variables

🔍

Filtering

Filter by cause of death and demographic variables

📊

Temporal Aggregation

Create daily, monthly, and annual time series

💾

Export and Import

Save and load data with complete metadata


📋 The climasus4r Workflow

Data analysis with climasus4r follows a logical, sequential pipeline, where the output of one function is the input to the next. This design, inspired by the tidyverse, makes the code more readable and easier to maintain.

sus_data_import() → sus_data_clean_encoding() → sus_data_standardize() → sus_data_create_variables() → sus_data_filter_cid() → sus_data_filter_demographics() → sus_data_aggregate()

Each function performs a specific processing step, such as importing, cleaning, standardizing, filtering, and aggregating the data. At the end of this pipeline, the data will be organized and ready for epidemiological analyses or for building time series.


1. Installation

The climasus4r package is available on GitHub and can be installed in two ways. We recommend Option 1 for most users.

If you don’t already have the remotes package installed, run the code below:

if (!require("remotes")) { install.packages("remotes")}

This is the fastest way to get the latest version:

# Install or update the package directly from GitHub
remotes::install_github("ByMaxAnjos/climasus4r", upgrade = "never")

Updates: climasus4r is under active development. To update, simply run the command above again. R will automatically overwrite the old version. After updating, it is recommended to restart the session (Menu: Session > Restart R).

Option 2: Installation from a Local File (.zip)

This option is recommended for environments with unstable connections, network restrictions, or use in training sessions with multiple users.

  1. Download the package: Click HERE to download the .zip file
  2. Extract the file: Extract the contents to an easily accessible folder (e.g., Downloads or Desktop)
  3. Install locally:
# IMPORTANT: Change the path below to the location where you saved the package
remotes::install_local(
  "C:/Path/To/Your/Folder/climasus4r-master",
  upgrade = "never"
)

2. Loading the Package

After installation, load the package whenever you start a new R session:

library(climasus4r)

3. Importing Data with sus_data_import()

The first step of the workflow consists of importing the data. The sus_data_import() function automates the download and reading of DATASUS microdata.

DATASUS has several information systems. In this tutorial, we will use SIM-DO (mortality) as an example.

Basic Example

Let’s import mortality data for the states of Rondônia ("RO") and Amazonas ("AM") for the years 2016 to 2017:

df_raw <- sus_data_import(
  system = "SIM-DO",
  year = 2016:2017,
  uf = c("RO", "AM"),
  lang = "en"
)

head(df_raw)

What happened? The sus_data_import() function automatically performed: 1. Download: Downloaded the .DBC files from the DATASUS FTP server 2. Decompression: Extracted the contents of the .DBC files 3. Reading: Read all files into a single data.frame 4. Metadata: Added information about the data’s origin

Optimizing Import: Caching and Parallel Processing

Using Cache to Avoid Re-downloads

By default (use_cache = TRUE), the function saves a copy of the downloaded data. On the next run with the same parameters, the data will be read directly from the cache.

df_custom_cache <- sus_data_import(
  system = "SIM-DO",
  year = 2018,
  uf = "RO",
  use_cache = TRUE,
  cache_dir = "~/.climasus4r_cache/data",
  lang = "en"
)
Speeding Things Up with Parallel Processing
# Download data from 3 states in parallel
df_parallel <- sus_data_import(
  system = "SIM-DO",
  year = 2018:2020,
  uf = c("RO", "PA", "MT"),
  use_cache = TRUE,
  parallel = TRUE,
  workers = 3,
  lang = "en"
)

How many workers should you use? A good starting point is the number of cores on your processor minus one (parallel::detectCores() - 1).


4. Cleaning Encoding with sus_data_clean_encoding()

DATASUS data frequently comes with character encoding issues. The sus_data_clean_encoding() function fixes this by converting all text columns to UTF-8.

# Fix character encoding
df_clean <- sus_data_clean_encoding(df_raw, lang = "en")

head(df_clean)

5. Standardizing Data with sus_data_standardize()

This step is crucial for analysis consistency. The function performs:

  • Renames columns to standardized names (e.g., CAUSABAS → underlying_cause_of_death)
  • Converts columns to the correct data types
  • Creates useful new variables such as age groups
df_std <- sus_data_standardize(df_clean, lang = "en")

head(df_std)

climasus_df object: From this point on, our data.frame has a special class that allows metadata to flow continuously between functions.


6. Creating Variables with sus_data_create_variables()

Before filtering, we frequently want to create derived variables. The sus_data_create_variables() function allows you to create:

  • Age groups: Custom groups or the standard IBGE breakdown
  • Calendar variables: Day of the week, month, season
  • Other variables: Birth decade, etc.
df_vars <- sus_data_create_variables(
  df_std,
  create_age_groups = TRUE,
  create_calendar_vars = TRUE,
  lang = "en"
)

head(df_vars)

New columns created: - faixa_etaria_ibge: 5-year age groups (IBGE standard) - dia_da_semana: Monday through Sunday - mes_nome: Month name - estacao: Season of the year - semana_do_ano: Week number


7. Filtering by Cause of Death with sus_data_filter_cid()

Let’s filter the data to select only deaths from respiratory diseases and cardiovascular diseases.

df_cid <- sus_data_filter_cid(
  df_vars,
  disease_group = c("respiratory", "cardiovascular"),
  lang = "en"
)

head(df_cid)

Exploring the Available Disease Groups

# Open the interactive exploration interface
sus_data_cid_select(lang = "en")

Commonly used disease groups: - respiratory (respiratory diseases) - cardiovascular (cardiovascular diseases) - neoplasms (neoplasms/cancer) - diabetes (diabetes mellitus) - infectious (infectious diseases)


8. Filtering by Demographic Variables with sus_data_filter_demographics()

Let’s refine the filter for a specific demographic subgroup:

  • Sex: Female
  • Age: Between 20 and 59 years
  • Race/Color: Black or Brown
df_demo <- sus_data_filter_demographics(
  df_cid,
  sex = "Feminino",
  age_range = c(20, 59),
  race = c("Preta", "Parda"),
  lang = "en"
)

head(df_demo)

Language: When lang = "pt", use the Portuguese values: "Feminino", "Masculino", "Preta", "Parda", etc. These category values come from the original DATASUS coding and are not translated even when lang = "en".


9. Temporal Aggregation with sus_data_aggregate()

Finally, let’s aggregate the records to create time series.

Monthly Aggregation

df_monthly <- sus_data_aggregate(
  df_demo,
  time_unit = "month",
  lang = "en"
)

head(df_monthly)

Daily Aggregation

df_daily <- sus_data_aggregate(
  df_demo,
  time_unit = "day",
  lang = "en"
)

head(df_daily)

10. Exporting Data with sus_data_export()

Supported Formats

Format Extension Recommended Use
RDS .rds R’s native format
Parquet .parquet Large volumes, interoperability
CSV .csv Universal, sharing
GeoParquet .geoparquet Optimized spatial data
Shapefile .shp Traditional GIS

Export Examples

# Export as CSV with metadata
sus_data_export(
  df_monthly,
  file_path = "obitos_mensais_resumo_cardio.csv",
  format = "csv",
  include_metadata = TRUE,
  lang = "en"
)
# Export as Parquet (more efficient)
sus_data_export(
  df_monthly,
  file_path = "obitos_mensais_resumo_cardio.parquet",
  format = "parquet",
  include_metadata = TRUE,
  lang = "en"
)

Export with Custom Metadata

sus_data_export(
  df_monthly,
  file_path = "analise_especifica.csv",
  format = "csv",
  include_metadata = TRUE,
  metadata = list(
    source_system = "SIM-DO",
    states = c("RO", "AM"),
    years = c(2016, 2017),
    disease_groups = c("respiratory", "cardiovascular"),
    author = "Your Name",
    project = "Climate and Health Study"
  ),
  lang = "en"
)

11. Importing Data with sus_data_read()

Reading a Single File

df_lido <- sus_data_read(
  path = "obitos_mensais_resumo_cardio.csv",
  format = "csv",
  read_metadata = TRUE,
  lang = "en"
)

# Access the metadata
sus_meta(df_lido, print_history = TRUE)

Batch Reading (Multiple Files)

# Read all CSV files from a folder
df_diretorio <- sus_data_read(
  path = "resultados_analises/",
  format = "csv",
  lang = "en"
)

Reading with Parallel Processing

df_paralelo <- sus_data_read(
  path = "pasta_de_dados/",
  format = "parquet",
  parallel = TRUE,
  workers = 4,
  read_metadata = TRUE,
  lang = "en"
)

🎉 Conclusion

Congratulations! You have completed the basic climasus4r workflow. In a few steps, you were able to:

  • Download and import raw DATASUS data in an optimized way
  • Clean, standardize, and enrich the data with new variables
  • Filter by epidemiological and demographic criteria
  • Create time series ready for analysis
  • Export and import data with complete metadata

📚 Next Steps

  1. Try other systems (system = "SIH" for hospitalizations)
  2. Test different states and years
  3. Explore different disease groups
  4. Combine with climate data for impact analyses
  5. See the full documentation: github.com/ByMaxAnjos/climasus4r

🌲 Have feedback or suggestions?

Do you have an idea for improvement or did you find a bug? Click the button below to open a new issue on GitHub and share your suggestions directly with us.

Open an issue on GitHub