Package 'khisr'

Title: An R Client to Retrieve Data from DHIS2
Description: Provides a user-friendly interface for interacting with the District Health Information Software 2 (DHIS2) instance. It streamlines data retrieval, empowering researchers, analysts, and healthcare professionals to obtain and utilize data efficiently.
Authors: David Kariuki [aut, cre, cph]
Maintainer: David Kariuki <[email protected]>
License: MIT + file LICENSE
Version: 1.0.6.9000
Built: 2024-11-06 05:58:29 UTC
Source: https://github.com/damurka/khisr

Help Index


Analytics Data Dimensions

Description

Constructs a dimensions expression for analytics queries based on specified property, operator, and values.

Usage

analytics_dimension(property, operator, values)

operator %.d% values

operator %.f% values

Arguments

property

A character string representing whether its dimension or filter. It only accepts 'dimension', 'filter'.

operator

A character string representing the property to filter on (e.g., 'dx', 'pe', 'ou').

values

A vector of values or semi-colon separated string items.

Details

DHIS2 organizes data using multiple dimensions, each with a unique identifier and a set of items that represent specific data points within that dimension.

  • Data elements (dx): Indicators, data set reporting rate metrics, data element operands, program indicators, program data elements, program attributes, validation rules.

  • Periods (pe): ISO periods (e.g., 202401) and relative periods (e.g., LAST_WEEK).

  • Organisation unit hierarchy (ou): Specific health facilities, districts, countries, and keywords for user location or its sub-units.

  • Category option combinations (co): Category option combo identifiers.

  • Attribute option combinations (ao): Category option combo identifiers.

  • Categories: Category option identifiers.

  • Data element group sets: Data element group identifiers.

  • Organisation unit group sets: Organisation unit group identifiers.

The infix operator used for filter and dimension includes:

  • ⁠%.d%⁠: Infix operator for constructing dimension filters. Equivalent to calling analytics_dimension("dimension", ...).

  • ⁠%.f%⁠: Infix operator for constructing filter filters. Equivalent to calling analytics_dimension("filter", ...).

Value

A spliced list with filter in the format property=operator:value

Examples

# Create a dimension for data element "DE_1234"
analytics_dimension('dimension', "dx", "DE_1234")

# Equivalent to the expression above
dx %.d% "DE_1234"

# Create a filter dimension for the period of January 2024
pe %.f% "202401"

# Create filter dimension for periods "202401" and "202402":
analytics_dimension("filter", "pe", c("202401", "202402"))

Retrieves Disaggregated Analytics Data from DHIS2

Description

get_analytics() retrieves disaggregated data from DHIS2 analytics tables for a specified period and data element(s), without performing any aggregation.

Usage

get_analytics(
  ...,
  return_type = c("uid", "name"),
  retry = 2,
  verbosity = 0,
  timeout = 60
)

Arguments

...

One or more analytics_dimension() parameters in key-value pairs. These define the analytics query, including data elements, periods, and organization units.

return_type

Optional argument specifying the return format for identifiers. defaults to 'uid'. Choose 'name' for human readable labels.

retry

Number of times to retry the API call in case of failure (defaults to 2).

verbosity

Level of HTTP information to print during the call:

  • 0: No output

  • 1: Show headers

  • 2: Show headers and bodies

  • 3: Show headers, bodies, and CURL status message.

timeout

Maximum number of seconds to wait for the API response.

Details

  • Retrieves data directly from DHIS2 analytics tables.

  • Allows specifying analytics dimensions, return format for identifiers, retry attempts, and logging verbosity.

Value

A tibble containing the disaggregated analytics data, or NULL if no data is retrieved.

Examples

# Clinical Breast Examination data elements
# XEX93uLsAm2 = CBE Abnormal
# cXe64Yk0QMY = CBE Normal
element_id <- c('cXe64Yk0QMY', 'XEX93uLsAm2')

# Download data from February 2023 to current date
data <- get_analytics(dx %.d% element_id, pe %.d% 'LAST_MONTH')
data

Retrieves Analytics Table Data

Description

[Experimental] get_analytics_by_level() fetches data from the DHIS2 analytics tables for a given period and data element(s), without performing any aggregation.

Usage

get_analytics_by_level(
  element_ids,
  start_date,
  end_date = NULL,
  level = 1,
  org_ids = NULL,
  ...,
  call = caller_env()
)

Arguments

element_ids

Required vector of data element IDs for which to retrieve data.

start_date

Required start date to retrieve data. It is required and in the format YYYY-MM-dd.

end_date

Optional ending date for data retrieval (default is the current date).

level

The desired organisation level of data (default: level 1)

org_ids

Optional list of organization units IDs to be filtered.

...

Other options that can be passed onto DHIS2 API.

call

The caller environment.

Details

  • Retrieves data directly from DHIS2 analytics tables.

  • Supports optional arguments for providing organization lists, data elements, and categories.

  • Allows specifying DHIS2 session objects, retry attempts, and logging verbosity.

Value

A tibble with detailed information, including:

  • Geographical identifiers (country, subnational, district, facility, depending on level)

  • Reporting period (month, year, fiscal year)

  • Data element names

  • Category options

  • Reported values

See Also

Examples

# Clinical Breast Examination data elements
# XEX93uLsAm2 = CBE Abnormal
# cXe64Yk0QMY = CBE Normal
element_id = c('cXe64Yk0QMY', 'XEX93uLsAm2')

# Download data from February 2023 to current date
data <- get_analytics_by_level(element_ids = element_id,
                               start_date = '2023-02-01')
data

Get Data Elements with Category Options

Description

[Experimental] get_data_elements_with_category_options() fetches data elements metadata with the category options from the DHIS2 API server.

Usage

get_data_elements_with_category_options(
  element_ids,
  auth = NULL,
  call = caller_env()
)

Arguments

element_ids

The data element identifiers whose details being retrieved

auth

The authentication object

call

The caller environment

Value

A tibble containing the following columns:

  • element_id - The unique identifier for the data element.

  • element - The name of the data element.

  • category - The category options for the elements

  • category_id - The unique identifier for the category options

Examples

# Fetch the data element metadata for particular element id
elements <- get_data_elements_with_category_options('htFuvGJRW1X')
elements

Retrieves Data Set Reporting Rate Metrics

Description

[Experimental] get_data_sets_by_level() fetches the data set reporting metrics. The metric can be REPORTING_RATE, REPORTING_RATE_ON_TIME, ACTUAL_REPORTS, ACTUAL_REPORTS_ON_TIME, EXPECTED_REPORTS.

Usage

get_data_sets_by_level(
  dataset_ids,
  start_date,
  end_date = NULL,
  level = 1,
  org_ids = NULL,
  ...,
  call = caller_env()
)

Arguments

dataset_ids

Required vector of data sets IDs for which to retrieve data. Required.

start_date

Optional start date to retrieve data. It is required and in the format YYYY-MM-dd.

end_date

Optional ending date for data retrieval (default is the current date).

level

Required desired organisation level of data (default: level 1) .

org_ids

Optional list of organization units IDs to be filtered.

...

Other options that can be passed onto DHIS2 API.

call

The caller environment.

Value

A tibble with detailed information, including:

  • Geographical identifiers (country, subnational, district, facility, depending on level)

  • Reporting period (month, year, fiscal year)

  • The reporting metric can be REPORTING_RATE, REPORTING_RATE_ON_TIME, ACTUAL_REPORTS, ACTUAL_REPORTS_ON_TIME, EXPECTED_REPORTS.

See Also

Examples

# The MoH 745 Cancer Screening Program Monthly Summary Form
dataset_id = c('WWh5hbCmvND')

# Download data from February 2023 to current date
data <- get_data_sets_by_level(dataset_ids = dataset_id,
                               start_date = '2023-02-01')
data

Get Metadata from a DHIS2 Instance

Description

get_metadata retrieves metadata for a specified endpoint of a DHIS2 instance.

Usage

get_metadata(
  endpoint,
  ...,
  fields = c("id", "name"),
  retry = 2,
  verbosity = 0,
  timeout = 60,
  call = caller_env()
)

Arguments

endpoint

The DHIS2 API endpoint for the metadata of interest (e.g., dataElements, organisationUnits endpoints).

...

One or more metadata_filter() parameters in key-value pairs.

fields

The specific columns to be returned in the data frame.

retry

Number of times to retry the API call in case of failure (defaults to 2).

verbosity

Level of HTTP information to print during the call:

  • 0: No output

  • 1: Show headers

  • 2: Show headers and bodies

  • 3: Show headers, bodies, and CURL status message.

timeout

Maximum number of seconds to wait for the DHIS2 API response.

call

The caller environment

Value

A tibble containing the DHIS2 metadata response.

Examples

# Get the categories metadata
get_metadata('categories')

# Get the datasets metadata with fields 'id,name,organisationUnits' and filter
# only the datasets with id 'WWh5hbCmvND'
get_metadata('dataSets',
             fields = 'id,name,organisationUnits[id,name,path]',
             id %.eq% 'WWh5hbCmvND')

# Get data elements filtered by dataElementGroups id
get_metadata('dataElements',
             dataElementGroups.id %.eq% 'IXd7DXxZqzL',
             fields = ':all')

Get Organisations by Level

Description

[Experimental] get_organisations_by_level() is an experimental function that retrieves the organisation units along with their parent units.

Usage

get_organisations_by_level(
  level = 1,
  org_ids = NULL,
  auth = NULL,
  call = caller_env()
)

Arguments

level

An integer specifying the desired organisation level (default level 1).

org_ids

Optional. A vector of organisation identifiers whose details are being retrieved.

auth

Optional. The authentication object

call

The call environment.

Value

A tibble containing the organisation units and their parent units up to the specified level.

Examples

# Fetch all the organisation units metadata
organisations <- get_organisations_by_level(level = 2)
organisations

Retrieve the Configured DHIS2 API Base URL

Description

This function returns the base URL for the DHIS2 API from the provided auth object, or falls back to the global auth credentials if auth is not provided.

Usage

khis_base_url(auth = NULL)

Arguments

auth

(Optional) An auth object containing the DHIS2 credentials. If not provided, the function retrieves the base URL from the global auth object.

Value

The DHIS2 base URL as a string, or NULL if no credentials are available.

See Also

Other credential functions: khis_cred(), khis_cred_clear(), khis_display_name(), khis_has_cred(), khis_username()

Examples

## Not run: 
    # Set the credentials using the global .auth object
    khis_cred(username = 'DHIS2 username',
              password = 'DHIS2 password',
              server = 'https://<dhis2-instance>')

    # Retrieve the DHIS2 instance API base URL (expect 'https://<dhis2-instance>')
    khis_base_url()

    # Clear credentials
    khis_cred_clear()

    # Retrieve the base URL again (expect 'NULL')
    khis_base_url()

## End(Not run)

Sets DHIS2 Credentials

Description

khis_cred() sets the credentials for accessing a DHIS2 instance.

Usage

khis_cred(
  username = NULL,
  password = NULL,
  server = NULL,
  api_version = NULL,
  config_path = NULL,
  base_url = deprecated()
)

Arguments

username

The DHIS2 username. Only required if configuration file not provided.

password

The DHIS2 password. Only required if configuration file not provided.

server

The server URL of the DHIS2 instance. Only required if configuration file not provided.

api_version

The API version of the DHIS2 instance (optional).

config_path

An optional path to a configuration file containing username and password. This is considered more secure than providing credentials directly in code.

base_url

Deprecated. The base URL of the DHIS2 instance. Use server instead.

Details

This function allows you to set the credentials for interacting with a DHIS2 server. You can either provide the username and password directly (less secure) or specify a path to a configuration file containing these credentials. Using a configuration file is recommended for improved security as it prevents credentials from being stored directly in your code.

Value

Auth object

See Also

Other credential functions: khis_base_url(), khis_cred_clear(), khis_display_name(), khis_has_cred(), khis_username()

Examples

## Not run: 
    # Option 1: Using a configuration file (recommended)
    # Assuming a configuration file named "credentials.json":
    khis_cred(config_path = "path/to/credentials.json")

    # Option 2: Providing credentials directly (less secure)
    khis_cred(username = "your_username",
              password = "your_password",
              server='https://<dhis2-instance>')

## End(Not run)

Clear the Credentials from Memory

Description

This function clears the DHIS2 credentials from memory. If an auth object is provided, it clears the credentials from that object. If no auth object is provided, it clears the global auth credentials.

Usage

khis_cred_clear(auth = NULL)

Arguments

auth

(Optional) An authentication object from which to clear credentials. If not provided, the credentials in the global auth object will be cleared.

Value

No return value, called for side effects.

See Also

Other credential functions: khis_base_url(), khis_cred(), khis_display_name(), khis_has_cred(), khis_username()

Examples

# Clear credentials from the global .auth object
khis_cred_clear()

Retrieve the Configured Display Name

Description

This function returns the display name from the configured profile in the provided auth object. If auth is not provided, it falls back to the global auth credentials.

Usage

khis_display_name(auth = NULL)

Arguments

auth

(Optional) An auth object containing DHIS2 credentials. If not provided, the function retrieves the display name from the global auth object.

Value

The display name as a string, or NULL if no profile or display name is available.

See Also

Other credential functions: khis_base_url(), khis_cred(), khis_cred_clear(), khis_has_cred(), khis_username()

Examples

## Not run: 
    # Set the credentials using global .auth object
    khis_cred(username = 'DHIS2 username',
              password = 'DHIS2 password',
              server = 'https://<dhis2-instance>')

    # Retrieve the display name from the global .auth profile
    khis_display_name()

    # Clear credentials
    khis_cred_clear()

    # Retrieve the display name again (expect 'NULL')
    khis_display_name()

## End(Not run)

Check if DHIS2 Credentials are Available

Description

This function checks whether valid credentials are available either in the provided auth object or in the global auth credentials object.

Usage

khis_has_cred(auth = NULL)

Arguments

auth

(Optional) An auth object containing DHIS2 credentials. If not provided, the function will check the global auth object for credentials.

Value

A boolean value indicating whether valid credentials are available.

See Also

Other credential functions: khis_base_url(), khis_cred(), khis_cred_clear(), khis_display_name(), khis_username()

Examples

## Not run: 
    # Set the credentials using global .auth object
    khis_cred(username = 'DHIS2 username',
              password = 'DHIS2 password',
              server = 'https://dhis2-instance/api')

    # Check if credentials are available. Should return TRUE
    khis_has_cred()

    # Clear global credentials
    khis_cred_clear()

    # Check if credentials are available. Should return FALSE
    khis_has_cred()

## End(Not run)

Retrieve the Configured Username

Description

This function returns the username from the configured credentials. If an auth object is provided, it retrieves the username from that object. Otherwise, it retrieves the username from the global auth object.

Usage

khis_username(auth = NULL)

Arguments

auth

(Optional) An auth object. If not provided, the function will retrieve the username from the global auth credentials.

Value

The username as a string, or NULL if no credentials are available.

See Also

Other credential functions: khis_base_url(), khis_cred(), khis_cred_clear(), khis_display_name(), khis_has_cred()

Examples

## Not run: 
    # Set the credentials using global .auth object
    khis_cred(username = 'DHIS2 username',
              password = 'DHIS2 password',
              server = 'https://<dhis2-instance>')

    # View the username (expect 'DHIS2 username')
    khis_username()

    # Clear credentials
    khis_cred_clear()

    # View the username (expect 'NULL')
    khis_username()

## End(Not run)

khisr Configuration

Description

Some aspects of khisr behaviour can be controlled via an option.

Temporarily suppress messages by enabling quiet mode within the provided code block.

Temporarily suppress messages within the specified environment.

Usage

with_khis_quiet(code)

local_khis_quiet(env = parent.frame())

Arguments

code

Code to execute quietly

env

The environment to use for scoping.

Value

No return value, called for side effects

No return value, called for side effects

No return value, called for side effects.

Messages

The khis_quiet option can be used to suppress messages form khisr. By default, khisr always messages, i.e. it is not quiet.

set khis_quiet to TRUE to suppress message, by one of these means, in order of decreasing scope:

  • Put options(khis_quiet = TRUE) in the start-up file, such as .Rprofile, or in your R script.

  • Use local_khis_quiet() to silence khisr in a specific scope.

  • Use with_khis_quite to run small bit of code silently.

local_khis_quiet and with_khis follow the conventions of the withr package.

Examples

## Not run: 
    # message: "The credentials have been set."
    khis_cred(username = 'username',
              password = 'password',
              server = 'https://<dhis2-instance>')

    # suppress messages for a small amount of code
    with_khis_quiet(
        khis_cred(username = 'username',
                  password = 'password',
                  server = 'https://<dhis2-instance>')
    )

## End(Not run)

## Not run: 
    # message: "The credentials have been set."
    khis_cred(username = 'username',
              password = 'password',
              server = 'https://<dhis2-instance>')

    # suppress messages for a in a specific scope
    local_khis_quiet()

    # no message
    khis_cred(username = 'username',
              password = 'password',
              server = 'https://<dhis2-instance>')

    # clear credentials
    khis_cred_clear()

## End(Not run)

Metadata Filter

Description

Formats a metadata filter to DHIS 2 comparison operators.

Usage

metadata_filter(property, operator, values, call = caller_env())

property %.eq% values

property %.ieq% values

property %.~eq% values

property %.ne% values

property %.Like% values

property %.~Like% values

property %.^Like% values

property %.~^Like% values

property %.Like$% values

property %.~Like$% values

property %.like% values

property %.~like% values

property %.^like% values

property %.~^like% values

property %.like$% values

property %.~like$% values

property %.gt% values

property %.ge% values

property %.lt% values

property %.le% values

property %.token% values

property %.~token% values

property %.in% values

property %.~in% values

Arguments

property

The property on the metadata you want to filter on

operator

The comparison operator you want to perform

values

The value to check against

call

description

Details

To filter the metadata there are several filter operations that can be applied to the returned list of metadata. The format of the filter itself is straight-forward and follows the pattern property:operator:value, where property is the property on the metadata you want to filter on, operator is the comparison operator you want to perform and value is the value to check against (not all operators require value). To view the operator see DHIS 2 Operator

  • ⁠%.eq%⁠ - Equality

  • ⁠%.ieq%⁠ - Case insensitive string, match exact

  • ⁠%.~eq%⁠ - Inequality

  • ⁠%.ne%⁠ - Inequality

  • ⁠%.Like%⁠ - Case sensitive string, match anywhere

  • ⁠%.~Like%⁠ - Case sensitive string, not match anywhere

  • ⁠%.^Like%⁠ - Case sensitive string, match start

  • ⁠%.~^Like%⁠ - Case sensitive string, not match start

  • ⁠%.Like$%⁠ - Case sensitive string, match end

  • ⁠%.~Like$%⁠ - Case sensitive string, not match end

  • ⁠%.like%⁠ - Case insensitive string, match anywhere

  • ⁠%.~like%⁠ - Case insensitive string, not match anywhere

  • ⁠ %.^like%⁠ - Case insensitive string, match start

  • ⁠%.~^like%⁠ - Case insensitive string, not match start

  • ⁠%.like$%⁠ - Case insensitive string, match end

  • ⁠%.~like$%⁠ - Case insensitive string, not match end

  • ⁠%.gt%⁠ - Greater than

  • ⁠%.ge%⁠ - Greater than or equal

  • ⁠%.lt%⁠ - Less than

  • ⁠%.le%⁠ - Less than or equal

  • ⁠%.token%⁠ - Match on multiple tokens in search property

  • ⁠%.~token%⁠ - Not match on multiple tokens in search property

  • ⁠%.in%⁠ - Find objects matching 1 or more values

  • ⁠%.~in%⁠ - Find objects not matching 1 or more values

Value

A spliced list with filter in the format property:operator:value

Examples

# Generate an equality filter
id %.eq% 'element_id'

# Finding multiple ids
'id' %.in% c('id1', 'id2', 'id3')

# Get all data elements which have a data set with id ID1
'dataSetElements.dataSet.id' %.eq% 'ID1'

# get data elements which are members of the ANC data element group
'dataElementGroups.id' %.eq% 'qfxEYY9xAl6'

# Get data elements which have any option set
metadata_filter('optionSet', '!null', NULL)

DHIS2 Metadata Helper Functions

Description

These functions simplify retrieving data from specific DHIS2 API endpoints using get_metadata().

Usage

get_categories(...)

get_category_combos(...)

get_category_option_combos(...)

get_category_option_group_sets(...)

get_category_option_groups(...)

get_category_options(...)

get_data_element_group_sets(...)

get_data_element_groups(...)

get_data_elements(...)

get_data_sets(...)

get_user_groups(...)

get_indicator_group_sets(...)

get_indicator_groups(...)

get_indicators(...)

get_option_group_sets(...)

get_option_groups(...)

get_option_sets(...)

get_options(...)

get_organisation_unit_groupsets(...)

get_organisation_unit_groups(...)

get_organisation_units(...)

get_organisation_unit_levels(...)

get_dimensions(...)

get_period_types(...)

get_user_profile()

Arguments

...

Arguments passed on to get_metadata

fields

The specific columns to be returned in the data frame.

retry

Number of times to retry the API call in case of failure (defaults to 2).

verbosity

Level of HTTP information to print during the call:

  • 0: No output

  • 1: Show headers

  • 2: Show headers and bodies

  • 3: Show headers, bodies, and CURL status message.

timeout

Maximum number of seconds to wait for the DHIS2 API response.

call

The caller environment

Value

A tibble containing the DHIS2 metadata response.

Examples

# Get all organisation units
get_organisation_units()

# Get all data elements
get_data_elements()

# Get data elements by element ids
get_data_elements(id %.in% c('VR7vdS7P0Gb', 'gQro1y7Rsbq'))

# Get datasets by name with the word 'MOH 705'
get_data_sets(name %.like% 'MOH 705')