Package {openNCAI}


Type: Package
Title: Calculates a Natural Capital Assets Index
Version: 0.1.0
Date: 2026-05-04
Description: Calculates a regional natural capital assets index (NCAI) following the methodology designed by NatureScot for Scotland as described in Albon, Balana, Brooker & Eastwood (2014) https://www.nature.scot/sites/default/files/2025-06/naturescot-commissioned-report-751.pdf and McKenna et al. (2019) <doi:10.1016/J.ECOLIND.2019.105645>. Processes habitat extent and condition data alongside metadata and weighting systems to produce a yearly single figure indexed relative to a base-year value of 100.
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
URL: https://github.com/oharakate/openNCAI
BugReports: https://github.com/oharakate/openNCAI/issues
Imports: dplyr, janitor, magrittr, openxlsx, readxl, rlang, slider, stats, stringr, tidyr
RoxygenNote: 7.3.3
VignetteBuilder: knitr
Suggests: ggplot2, knitr, rmarkdown, rprojroot, testthat (≥ 3.0.0), tibble
Config/testthat/edition: 3
Depends: R (≥ 4.1.0)
NeedsCompilation: no
Packaged: 2026-05-08 07:35:49 UTC; kateohara
Author: Kate O'Hara [aut, cre]
Maintainer: Kate O'Hara <k.a.ohara@stir.ac.uk>
Repository: CRAN
Date/Publication: 2026-05-13 07:20:07 UTC

openNCAI: Calculates a Natural Capital Assets Index

Description

Calculates a regional natural capital assets index (NCAI) following the methodology designed by NatureScot for Scotland as described in Albon, Balana, Brooker & Eastwood (2014) https://www.nature.scot/sites/default/files/2025-06/naturescot-commissioned-report-751.pdf and McKenna et al. (2019) doi:10.1016/J.ECOLIND.2019.105645. Processes habitat extent and condition data alongside metadata and weighting systems to produce a yearly single figure indexed relative to a base-year value of 100.

Author(s)

Maintainer: Kate O'Hara k.a.ohara@stir.ac.uk

See Also

Useful links:


Build All Natural Capital Asset Matrices

Description

Orchestrates the generation of asset matrices for every year in the series. Each matrix represents the final "Year Sheet" in the NatureScot account methodology, combining condition, wellbeing, and extent.

Usage

build_all_ncai_matrices(
  tyf_list,
  wellbeing_potential_base,
  habitat_extent,
  year_one = NULL,
  year_list,
  habitat_labels
)

Arguments

tyf_list

A named list of Total Yearly Flow (TYF) matrices (one per year).

wellbeing_potential_base

A data frame representing the base wellbeing values (year one habitat extent weighted by provision per unit and demand).

habitat_extent

A data frame where rows represent habitats and columns represent total extent per year.

year_one

The base year (e.g., 2000) used for indexing extent.

year_list

The list of years over which the index is calculated. By default, year_one is taken as the first item in this list.

habitat_labels

A character vector of habitat names to be applied to the resulting data frames.

Value

A named list of data frames, one for each year. Each data frame displays the calculated natural capital assets by habitat and service.


Build All Total Yearly Flow Matrices (TYFs)

Description

Orchestrates the full process of generating the Total Yearly Flow matrices for every year in the series. It builds the indicator-specific contribution matrices (YWCCMs) and then aggregates and normalizes them.

Usage

build_all_tyfs(
  raw_cis,
  year_list,
  ciwms_list,
  total_indicator_relevances,
  total_indicator_relevances_constant
)

Arguments

raw_cis

A data frame of raw condition indicator scores.

year_list

A vector of all years in the account (e.g., 2000:2022).

ciwms_list

A named list of Condition Indicator Weighting Matrices (CIWMs).

total_indicator_relevances

The Total Indicator Relevance matrix (output from calc_total_indicator_relevances).

total_indicator_relevances_constant

A numeric value (usually 2) used for normalization.

Value

A named list of matrices, one for each year in year_list. Each matrix represents the aggregated flow of ecosystem services for that year.


Build Yearly Weighted Condition Contribution Matrices (YWCCMs)

Description

Generates a list of matrices where each indicator's relevance weighting (CIWM) is multiplied by its indexed condition score for a given year.

Usage

build_all_ywccms(raw_cis, year, year_list, ciwms_list)

Arguments

raw_cis

A data frame of raw condition indicator scores.

year

The year for which to build the matrices.

year_list

A vector of all years in the account (to establish base year).

ciwms_list

A named list of Condition Indicator Weighting Matrices (CIWMs).

Value

A named list of matrices (YWCCMs), one for each indicator.


Build Condition Indicator Weight Matrices (CIWM)

Description

Converts relevance matrices (CIRM) into weight matrices (CIWM) by multiplying the relevance scores by the indicator's importance weights (per ecosystem service type) as defined in the Indicator Directory.

Usage

build_ciwm_list(
  cirm_list,
  indicator_directory,
  es_label_tree,
  habitats_label_tree = NULL
)

Arguments

cirm_list

A named list of data frames. Names are condition indicator labels. Data frames hold a matrix of binary values denoting whether the Condition Indicator is relevant to each habitat/service combination. Names must match the labels in the ci_id column of indicator_directory.

indicator_directory

A data frame containing weights denoting the relevance of each condition indicator to each ecosystem service type. Must include a column of condition indicator labels for matching called ci_id. Weight columns must match the top level names from the es_label_tree.

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services (as character vectors) within service type group (as list object names). Syntactical names only (no spaces or special characters).

habitats_label_tree

A named list of character vectors representing the hierarchy of habitats (as character vectors, typically EUNIS Level 2) within broad habitats (as list object names, typically EUNIS Level 1). Syntactical names only (no spaces or special characters). The habitats label tree is optional; if supplied a labelled data frame will be returned.

Value

A named list of data frames, one list object for each Condition Indicator each containing the weighted relevance of that indicator to each combination of habitats and ecosystem services.


Build a Single Year's Natural Capital Asset Matrix

Description

Calculates the Natural Capital Asset (NCA) matrix for a specific target year. It combines the Total Yearly Flow (condition) with the Wellbeing Base and adjusts for the change in Habitat Extent relative to a base year.

Usage

build_ncai_matrix(
  tyf,
  wellbeing_potential_base,
  habitat_extent,
  target_year,
  year_one,
  habitat_labels
)

Arguments

tyf

A matrix of Total Yearly Flows for the target year.

wellbeing_potential_base

A matrix of base wellbeing values.

habitat_extent

A data frame of habitat extent values.

target_year

The specific year to calculate.

year_one

The base year for extent indexing.

Details

The final calculation follows the formula: (TYF \times Wellbeing Base \times Extent Index) / 10,000. The Extent Index is the target year's extent divided by the base year's extent, multiplied by 100.

Value

A data frame of natural capital assets for the target year.


Build Total Yearly Flow (TYF) for a Single Year

Description

Aggregates a list of YWCCMs and normalizes the sum against the Total Indicator Relevances matrix.

Usage

build_tyf(
  list_of_ywccms,
  total_indicator_relevances,
  total_indicator_relevances_constant
)

Arguments

list_of_ywccms

A list of Yearly Weighted Condition Contribution Matrices.

total_indicator_relevances

The Total Indicator Relevance matrix.

total_indicator_relevances_constant

Numeric. Added to denominator for stability and numerator for indexing.

Value

A numeric matrix for one year.


Calculate the Ecosystem Service Potential Base

Description

Multiply the Provision Per Unit (weights) by the habitat extent in the baseline year of the index.

Usage

calc_es_potential_base(
  provision_per_unit_weights,
  habitat_extent,
  year_list,
  year_one = NULL,
  habitats_label_tree,
  es_label_tree
)

Arguments

provision_per_unit_weights

A data frame containing the ecosystem service provision potential per unit weights. Row order must match the expanded habitats label tree and column order must match the expanded ES label tree.

habitat_extent

A data frame containing data representing the extent (area) of each habitat in each year of the index. Rows = habitats. Columns = years. There must be a column to match the identified baseline year. Row order must match the expanded habitats label tree.

year_list

A vector (character or numeric) of the years over which the index is to be calculated.

year_one

Optional. The specific year from habitat_extent to use as the baseline for extent. If NULL (default), uses the first element of year_list.

habitats_label_tree

A named list of character vectors representing the hierarchy of habitats.

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services.

Value

A labelled data frame with the same dimensions as 'provision_per_unit_weights'.


Calculate Importance Weights using Hierarchical Named Lists

Description

This function calculates the final importance weights for ecosystem services by combining between-group scores (broad categories) and within-group scores (specific services). It uses a name-aware approach, matching list names to the provided label tree to ensure scores are applied to the correct categories.

Usage

calc_importance_weights(between_scores, within_scores, es_label_tree)

Arguments

between_scores

A named list of numeric values where names match the top-level categories in es_label_tree.

within_scores

A named list where each element is itself a named list (or named vector) of numeric scores. The top-level names must match the categories in es_label_tree, and the inner names must match the specific ecosystem service labels.

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services (as character vectors) within service type group (as list object names). Syntactical names only (no spaces or special characters).

Details

The function first normalizes the between-group scores to 100. For each category, it then normalizes the within-group scores and multiplies them by the category's broad weight. If a category has a total score of zero, all services within it are assigned a weight of 0.

Value

A single-row data frame where columns are the individual ecosystem services and the values are their calculated importance weights, scaled by both between-group and within-group priorities.


Calculate NCAI Broken Down by Broad Habitat

Description

Calculates the index subsetted by broad habitat

Usage

calc_ncai_by_bh(
  total_assets_matrix_list,
  habitats_label_tree,
  year_one = NULL,
  ...
)

Arguments

total_assets_matrix_list

A named list of annual asset data frames.

habitats_label_tree

A named list where each element is a character vector of habitat labels (row names).

year_one

Optional: year to index around. Default is year one of the year_list.

...

Additional arguments passed to calc_ncai.

Value

A list of NCAI data frames, one for each habitat group.


Calculate NCAI Broken Down by Ecosystem Service Type

Description

Calculate the index subsetted by ecosystem service type.

Usage

calc_ncai_by_st(total_assets_matrix_list, es_label_tree, year_one = NULL, ...)

Arguments

total_assets_matrix_list

A named list of annual asset data frames.

es_label_tree

A named list where each element is a character vector of ecosystem service labels (column names).

year_one

Optional: the year to index around. Default is the first year of the year_list.

...

Additional arguments passed to calc_ncai (e.g., smoothing_weights).

Value

A list of NCAI data frames, one for each ecosystem service group.


Calculate Weights from Provision Per Unit Scores

Description

Converts scores denoting ecosystem service Provision Per Unit of habitats to weights by dividing by either a common denominator, or a matrix of custom divisors per habitat/ecosystem service combination.

Usage

calc_provision_per_unit_weights(
  provision_per_unit_scores,
  divisor = 5,
  custom_divisor_matrix = NULL,
  habitats_label_tree = NULL,
  es_label_tree = NULL
)

Arguments

provision_per_unit_scores

A numeric data frame where rows represent habitat types and columns represent ecosystem services and cells denote the exemplary capacity of each habitat type to provide each ecosystem service.

divisor

A single numeric value by which Provision Per Unit scores are divided to calculate the weights, typically the number out of which scores have been awarded. Default value is 5. Alternatively a custom_divisor_matrix may be specified.

custom_divisor_matrix

Optional. A numeric data frame of the same dimensions as 'provision_per_unit', containing the number by which the score should be divided for each habitat/service combination.

habitats_label_tree

A named list of character vectors representing the hierarchy of habitats (as character vectors, typically EUNIS Level 2) within broad habitats (as list object names, typically EUNIS Level 1). Syntactical names only (no spaces or special characters). The habitats label tree is optional and if supplied will be used to label the returned data frame.

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services (as character vectors) within service type group (as list object names). Syntactical names only (no spaces or special characters). The ES label tree is optional and if supplied will be used to label the returned data frame.

Value

A labelled data frame of the same dimensions as provision_per_unit_scores containing the calculated Provision Per Unit weights.

Warning

Either divisor or custom_divisor_matrix must be provided. If custom_divisor_matrix is provided, it must have the same dimensions as provision_per_unit.


Calculate Total Indicator Relevances

Description

Aggregates a list of weighted condition indicator matrices into a single matrix representing the total relevance of all selected indicators to each habitat-service combination.

Usage

calc_total_indicator_relevances(
  all_ciwms_list,
  total_indicator_relevances_constant
)

Arguments

all_ciwms_list

A list of Condition Indicator Weighting Matrices (CIWMs). Each element in the list must be a data frame where rows correspond to habitats and columns to ecosystem services.

total_indicator_relevances_constant

A numeric value added to the aggregated total prevent zero-division errors in later calculations.

Details

The function uses Reduce("+", ...) to perform element-wise addition across all matrices in the input list. A constant is then added to every cell to ensure that subsequent divisions (e.g., when calculating the NCAI) do not encounter zeros.

Value

A data frame of numeric values representing the summed relevance scores plus the constant, with the same dimensions as the input matrices.


Worker Function to Calculate Weighted Habitat Extent Time Series

Description

An internal helper that multiplies a weight matrix by an indexed habitat extent vector across a time series.

Usage

calc_weighted_habitat_extent(
  habitat_extent,
  year_one,
  weight_matrix,
  as_matrices = FALSE
)

Arguments

habitat_extent

A matrix or data frame where columns represent years and rows represent habitats.

year_one

Character or Numeric. The baseline year for indexing.

weight_matrix

A matrix (e.g., ES Potential Base or Wellbeing Base) to be multiplied by the indexed extent.

as_matrices

Logical. If TRUE, returns annual matrices; if FALSE, returns a smoothed index data frame.

Value

Depending on as_matrices, either a named list of matrices or an indexed data frame.


Scales the Ecosystem Service (ES) Potential Base by the Importance Weight for each service to generate the Wellbeing Base. ES Potential Base is expressed as each habitat's contribution as a proportion of the total potential for that service. Label trees may be passed in for optional labelling of the output data frame.

Description

Scales the Ecosystem Service (ES) Potential Base by the Importance Weight for each service to generate the Wellbeing Base. ES Potential Base is expressed as each habitat's contribution as a proportion of the total potential for that service. Label trees may be passed in for optional labelling of the output data frame.

Usage

calc_wellbeing_potential_base(
  es_potential_base,
  importance_weights,
  habitats_label_tree = NULL,
  es_label_tree = NULL
)

Arguments

es_potential_base

A matrix (or data frame) of habitat (rows) by ecosystem service (columns) containing weights to denote the potential of each habitat to provide each ecosystem service, calculated for the baseline year (Year One).

importance_weights

A vector of weights denoting the importance of each ecosystem service in the area of interest.

habitats_label_tree

A named list of character vectors representing the hierarchy of habitats (as character vectors, typically EUNIS Level 2) within broad habitats (as list object names, typically EUNIS Level 1). Syntactical names only (no spaces or special characters). The habitats label tree is optional and if supplied will be used to label the returned data frame.

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services (as character vectors) within service type group (as list object names). Syntactical names only (no spaces or special characters). The ES label tree is optional and if supplied will be used to label the returned data frame.

Value

A data frame representing the Wellbeing Base.

Examples

# Assuming es_potential_base and importance_weights are already calculated:
# wellbeing_potential_base_matrix <- calc_wellbeing_potential_base(
#   es_potential_base = es_potential_base_matrix,
#   importance_weights = weights_vector,
#   habitats_label_tree = habitats_tree,
#   es_label_tree = es_tree
# )

Create an NCAI Data Entry Template

Description

Generates a highly formatted, protected Excel (.xlsx) workbook containing the necessary sheets for a user to populate an openNCAI account. The template includes internal logic for habitat and ecosystem service trees, automated styling, and cell locking to ensure data integrity for subsequent re-import. Note that the habitats and ecosystem service label trees passed here may be used to subsequently read in the data with read_ncai_template().

Usage

create_ncai_template(
  template_out,
  habitats_label_tree,
  es_label_tree,
  ci_names,
  year_list,
  overwrite = FALSE,
  habitat_extent = NULL,
  provision_per_unit_scores = NULL,
  between_importance_scores = NULL,
  within_importance_scores = NULL,
  ci_scores = NULL,
  indicator_directory = NULL,
  ci_relevance_matrices = NULL
)

Arguments

template_out

A string representing the file path where the .xlsx will be saved.

habitats_label_tree

A named list of character vectors representing the habitat hierarchy. Names: broad habitats, typically EUNIS level 1. Character vector items: typically EUNIS level 2 habitats.

es_label_tree

A named list of character vectors representing the ecosystem service hierarchy. Names: typically SEEA ecosystem service types. Character vector items: typically CICES-type ecosystem services.

ci_names

A character vector of condition indicator names.

year_list

A vector of years (numeric or character) to be included in the account.

overwrite

Logical. If TRUE, an existing file at template_out will be overwritten without warning. Default is FALSE to prevent accidental loss of manually entered data.

habitat_extent

Optional data frame of existing habitat extent data. Row and column order and dimensions MUST matched label trees/year list.

provision_per_unit_scores

Optional data frame of existing ES Potential Unit scores. Row and column order MUST match lower levels of habitats_label_tree and es_label_tree.

between_importance_scores

Optional list of ecosystem service type importance weights. Order MUST match names of es_label_tree.

within_importance_scores

Optional list of lists of weights for specific services. Order MUST match the order and dimensions of the lower level of es_label_tree.

ci_scores

Optional data frame of existing condition indicator scores. Rows and columns MUST match dimensions and order of year_list and ci_names.

indicator_directory

Optional data frame of existing indicator salience data. Row order and length MUST match ci_names. Column order and length MUST match es_label_tree names.

ci_relevance_matrices

Optional list of existing binary relevance matrices. Matrix list order and length must mach ci_names. Each matrix row and column order MUST match lower levels of habitats_label_tree and es_label_tree.

Details

Optional arguments to pre-populate the template with data assume that the passed-in data matches those of the label trees, year list and condition indicator list as relevant. Users are recommended to create an empty template first to verify the required formats before attempting to pass in data.

Value

Generates an Excel file at the specified path and returns a message of success.

Examples


# 1. Define the habitat hierarchy
habitat_label_tree <- list(
  'B. Coastal Habitats' = c(
    "Coastal vegetated shingle",
    "Coastal dunes and sandy shores"
  ),
  'E. Grasslands' = c(
    "Dry Grasslands",
    "Mesic Grasslands"
  )
)

# 2. Define the ecosystem service hierarchy
ecosystem_service_label_tree <- list(
  'PROVISIONING' = c(
    "1.1 Cultivated Crops",
    "1.2 Reared Animals And Their Outputs"
  ),
  'CULTURAL' = c(
    "3.5. Existence & bequest"
  )
)

# 3. Define indicators and temporal scope
condition_indicator_list <- c("National Water Quality Index", "AgriSCOR")
list_of_years <- 2020:2025

# 4. Generate the template in a temporary location
# tempfile() ensures a valid path that won't clutter your working directory.
tmp_path <- tempfile(fileext = ".xlsx")

create_ncai_template(
  template_out = tmp_path,
  habitats_label_tree = habitat_label_tree,
  es_label_tree = ecosystem_service_label_tree,
  ci_names = condition_indicator_list,
  year_list = list_of_years
)

message("Template successfully created at: ", tmp_path)


Calculate Habitat Extent (Indexed) for a Target Year

Description

This helper function extracts habitat extent vectors for a specific target year and a baseline year, then calculates a percentage-based index.

Usage

get_habitat_extent_year_vec(target_year, year_one, habitat_extent)

Arguments

target_year

The year to be indexed (numeric or character).

year_one

The baseline year used as the denominator (numeric or character).

habitat_extent

A matrix or data frame where columns represent years and rows represent habitat types/locations.

Details

The function performs the calculation:
(Target Extent / Baseline Extent) * 100

Value

A numeric vector of the same length as the number of rows in habitat_extent, representing the extent of each habitat in the target_year as a percentage of its extent in year_one.


Main User Interface for the Natural Capital Asset Index (NCAI)

Description

This is the primary function for calculating the NCAI. It processes habitat extent, condition scores, and importance weights through the full NCAI pipeline, with options to return intermediate matrices or specific breakdowns.

Usage

get_ncai(
  habitat_extent,
  ci_scores,
  habitats_label_tree,
  es_label_tree,
  year_list,
  year_one = NULL,
  provision_per_unit_scores,
  provision_per_unit_divisor = 5,
  custom_divisor_matrix = NULL,
  between_importance_scores,
  within_importance_scores,
  ci_relevance_matrices,
  indicator_directory,
  total_indicator_relevances_constant = 2,
  smoothing_weights = c(0.2, 0.4, 0.6, 0.8, 1),
  return = c("overall_ncai", "by_ecosystem_service_type", "by_broad_habitat",
    "wellbeing_index", "flow_of_es_index", "yearly_ncai_matrices",
    "yearly_wellbeing_matrices", "flow_of_es_matrices", "es_potential_base",
    "wellbeing_potential_base", "flow_of_es_base", "everything")
)

Arguments

habitat_extent

A data frame of habitat area/extent per year.

ci_scores

A matrix of condition indicator scores.

habitats_label_tree

A named list defining the hierarchy of habitats.

es_label_tree

A named list defining the hierarchy of ecosystem services.

year_list

A vector (character or numeric) of years for the index.

year_one

Optional. The baseline year for indexing (where index = 100). Defaults to the first year in year_list.

provision_per_unit_scores

A data frame of Ecosystem Service Provision Potential per Unit.

provision_per_unit_divisor

Numeric. A standard divisor to convert Provision Per Unit scores to weights; the number out of which Provision Per Unit scores have been awarded. Default value is 5. Alternatively, a custom_divisor_matrix may be provided.

custom_divisor_matrix

Optional. A matrix of divisors specific to habitat/service combinations.

between_importance_scores

Scores representing the relative importance between different ecosystem service types.

within_importance_scores

Scores representing the relative importance within ecosystem service types.

ci_relevance_matrices

Condition Indicator Relevance Matrices list.

indicator_directory

Directory mapping indicators to services/habitats.

total_indicator_relevances_constant

Numeric. The constant used in the Total Indicator Relevance calculation. Defaults to 2.

smoothing_weights

Numeric vector of weights for 5-year trailing smoothing. Defaults to c(0.2, 0.4, 0.6, 0.8, 1.0).

return

Character. Specifies the object to return. Options include:

  • "overall_ncai": The standard overall NCAI data frame (default).

  • "by_ecosystem_service_type": NCAI broken down by Ecosystem Service Type.

  • "by_broad_habitat": NCAI broken down by Broad Habitat.

  • "wellbeing_index": The potential wellbeing contribution of the habitats (before weighting by likely flow of services) over the years, indexed.

  • "flow_of_es_index": The likely flow of ecosystem services (based on information from condition indicators) over the years, indexed.

  • "yearly_ncai_matrices": The overall NCAI in its unaggregated form, expressed as yearly matrices of value per habitat/ecosystem service.

  • "yearly_wellbeing_matrices": The yearly wellbeing potential in its unaggregated form, expressed as yearly matrices of value per habitat/ecosystem service.

  • "yearly_flow_of_es_matrices": The yearly likely flow of ecosystem services in its unaggregated form, expressed as yearly matrices of value per habitat/ecosystem service.

  • "es_potential_base": The Ecosystem Service Potential Base matrix, i.e. the habitat extent weighted weighted by exemplary provision-per-unit scores in year one.

  • "wellbeing_potential_base": The Wellbeing Potential Base, ie. year one potential wellbeing matrix.

  • "flow_of_es_base": The year one likely flow of services matrix.

  • "everything": A named list containing all of the above.

Details

Mandatory Inputs: Users must provide either an provision_per_unit_divisor or a custom_divisor_matrix to convert potential scores into weights.

Smoothing and Baseline Years: The smoothed index is calculated using a 5-year trailing window. If year_one is set to a year other than the first year of the dataset, the smoothed_index value for that baseline year will likely not be exactly 100. This is because the smoothing reflects the trend of the preceding 4 years. The raw_index will always remain anchored at 100 for the year_one.

Value

An object of the type specified by the return argument. Typically a data frame or a named list of NCAI components.

Examples

# Calculate the NCAI using the bundled NatureScot sample data
ncai_objects <- get_ncai(
  habitat_extent = ns_habitat_extent,
  ci_scores = ns_ci_scores,
  habitats_label_tree = ns_habitats_label_tree,
  es_label_tree = ns_es_label_tree,
  year_list = ns_year_list,
  provision_per_unit_scores = ns_provision_per_unit_scores,
  custom_divisor_matrix = ns_custom_divisor_matrix,
  between_importance_scores = ns_between_importance_scores,
  within_importance_scores = ns_within_importance_scores,
  ci_relevance_matrices = ns_ci_relevance_matrices,
  indicator_directory = ns_indicator_directory,
  return = "everything"
)

# View the final indexed results
names(ncai_objects)
head(ncai_objects$overall_ncai)

Extract List of Condition Indicator Relevance Matrices (CIRMs)

Description

Extract List of Condition Indicator Relevance Matrices (CIRMs)

Usage

get_ns_cirm_list(
  path,
  sheet_list,
  matrix_range,
  ci_ids,
  all_service_labels,
  all_habitat_labels
)

Arguments

path

Path to Excel source.

sheet_list

Vector of sheet indices to iterate through.

matrix_range

Excel range for the binary matrices.

ci_ids

Vector of indicator IDs.

all_service_labels

Flat vector of all service labels.

all_habitat_labels

Flat vector of all habitat labels.


Extract Ecosystem Service Importance Scores

Description

Extract Ecosystem Service Importance Scores

Usage

get_ns_importance_scores(path, sheet, importance_ranges, es_tree)

Arguments

path

Path to Excel source.

sheet

Sheet index.

importance_ranges

Named list of Excel ranges for each service type.

es_tree

The cleaned ES label tree.


Extract Indexed Condition Score for a Specific Indicator

Description

Retrieves and indexes (base 100) a condition score for a single indicator.

Usage

get_yearly_condition(raw_cis, year_to_get, ci_num, year_list)

Arguments

raw_cis

Data frame of raw condition scores.

year_to_get

Target year.

ci_num

Indicator column index or name.

year_list

Vector of years (index 1 is base year).

Value

A numeric indexed score.


Get Yearly Ecosystem Service Flow Rates

Description

This high-level function orchestrates the transformation of raw condition scores into normalized Total Yearly Flow (TYF) matrices. It builds the weighted relevance matrices (CIWMs), calculates the total indicator relevances, and processes every year in the series.

Usage

get_yearly_flow(
  cirm_list,
  indicator_directory,
  es_label_tree,
  habitats_label_tree,
  ci_scores,
  year_list,
  total_indicator_relevances_constant = 2
)

Arguments

cirm_list

A list of Condition Indicator Relevance Matrices.

indicator_directory

A data frame containing relevance weights for each indicator.

es_label_tree

A named list of ecosystem service labels.

habitats_label_tree

A named list of habitat labels.

ci_scores

A data frame or matrix of raw condition scores (years as rows).

year_list

A vector of years to be processed.

total_indicator_relevances_constant

A numeric constant (default 2) to prevent zero-division and ensure indexing congruency.

Value

A named list of Total Yearly Flow (TYF) matrices, one for each year in year_list.


Calculate Yearly Potential Provision of Ecosystem Services

Description

Calculates the potential provision time series by multiplying indexed habitat extent by the Ecosystem Service (ES) Potential Base.

Usage

get_yearly_potential_provision(
  habitat_extent,
  year_one,
  es_potential_base,
  as_matrices = FALSE
)

Arguments

habitat_extent

A matrix or data frame where columns represent years and rows represent habitats.

year_one

Character or Numeric. The baseline year for indexing.

es_potential_base

A matrix or data frame of Ecosystem Service Potential Base values.

as_matrices

Logical. If TRUE, returns annual matrices; if FALSE, returns a smoothed index data frame.

Value

Depending on the value of as_matrices:


Calculate Yearly Potential Wellbeing Contribution

Description

Calculates the potential wellbeing contribution time series by multiplying indexed habitat extent by the Wellbeing Base. It can be understood as the the potential wellbeing contribution of the habitat assets over the years, before weighting by likely flow of ecosystem services based on habitat condition.

Usage

get_yearly_potential_wellbeing(
  habitat_extent,
  year_one,
  wellbeing_potential_base,
  as_matrices = FALSE
)

Arguments

habitat_extent

A matrix or data frame where columns represent years and rows represent habitats.

year_one

Character or Numeric. The baseline year for indexing.

wellbeing_potential_base

A matrix or data frame of Wellbeing Potential Base values.

as_matrices

Logical. If TRUE, returns annual matrices; if FALSE, returns a smoothed index data frame.

Value

Depending on the value of as_matrices:


Import and Process Natural Capital Account Data

Description

This is the primary wrapper function for importing data from the NatureScot NCAI Excel template. It extracts habitat classifications, ecosystem service weights, condition indicators, and yearly measurements, bundling them into a structured list for subsequent index calculations.

Usage

import_ns_data(
  path,
  year_list = 2000:2022,
  total_indicator_relevances_constant = 2
)

Arguments

path

A string representing the file path to the .xlsx data source.

year_list

A vector of years to include in the account (e.g., 2000:2022).

total_indicator_relevances_constant

A numeric constant added to the Total Indicator Relevances.

Value

A named list containing 14 components:

A named list containing structured NCAI data objects.


Import Reference Data for Replication Testing

Description

Imports selected sheets and ranges from the NatureScot NCAI spreadsheet that contain the intermediate and final results of their calculations. This data is used as a "gold standard" to ensure the 'openNCAI' package replicates the methodology reliably.

Usage

import_ns_testing_data(path, habitats_label_tree, es_label_tree, year_list)

Arguments

path

A string representing the file path to the NatureScot .xlsx source.

habitats_label_tree

A named list of habitat labels used for matrix row naming.

es_label_tree

A named list of ecosystem service labels used for matrix column naming.

Value

A nested list containing:


Index matrices and apply smoothing

Description

This function calculates the raw and smoothed Natural Capital Asset Index from a list of yearly asset matrices, e.g. the NCAI matrices. It anchors the index to a specific baseline year and applies a weighted trailing moving average.

Usage

index_and_smooth(
  matrix_list,
  smoothing_weights = c(0.2, 0.4, 0.6, 0.8, 1),
  year_one = names(matrix_list)[[1]]
)

Arguments

matrix_list

A named list of matrices, where each matrix represents the values for a specific year, with rows = habitats and columns = ecosystem service type. The names of the list must be the years.

smoothing_weights

A numeric vector of weights used for the trailing 5-year weighted smoothing. Defaults to c(0.2, 0.4, 0.6, 0.8, 1.0).

year_one

Character or Numeric. The year used as the baseline (where index = 100). Defaults to the first name in matrix_list.

Details

Smoothing and Baseline Years: The smoothed index is calculated using a 5-year trailing window via a weighted moving average (using the slider package). If year_one is set to a year other than the first year of the dataset, the smoothed_index value for that baseline year will likely not be exactly 100. This is because the smoothing reflects the trend of the preceding 4 years. The raw_index will always remain anchored at 100 for the year_one.

Value

A data frame containing:


Label NCAI Habitat/Ecosystem Service Matrix This function takes a habitat/ecosystem service matrix of values used in openNCAI and returns it as a data frame with the habitat and ecosystem service labels applied.

Description

Label NCAI Habitat/Ecosystem Service Matrix This function takes a habitat/ecosystem service matrix of values used in openNCAI and returns it as a data frame with the habitat and ecosystem service labels applied.

Usage

label_ncai_matrix(matrix, habitats_label_tree, es_label_tree)

Arguments

matrix

A matrix of values, e.g. scores, weights, where rows are habitats and columns are ecosystem services

habitats_label_tree

A named list of character vectors representing the hierarchy of habitats (as character vectors, typically EUNIS Level 2) within broad habitats (as list object names, typically EUNIS Level 1). Syntactical names only (no spaces or special characters).

es_label_tree

A named list of character vectors representing the hierarchy of ecosystem services (as character vectors) within service type group (as list object names). Syntactical names only (no spaces or special characters).

Value

A labelled data frame.


Generate Custom Divisor Matrix

Description

Creates a matrix of normalization divisors (e.g., scoring scales) for every habitat-service combination. It allows for specific adjustments where certain services or habitats use a different scale (e.g., a 1-point scale instead of a 5-point scale).

Usage

make_custom_divisor_matrix(
  all_habitat_labels,
  all_es_labels,
  habitats_to_adjust,
  services_to_adjust,
  usual_divisor,
  custom_divisor
)

Arguments

all_habitat_labels

A character vector of all cleaned habitat names.

all_es_labels

A character vector of all cleaned ecosystem service names.

habitats_to_adjust

A character vector of habitat shorthands or patterns (e.g., "b1") to be matched for custom divisors.

services_to_adjust

A character vector of service shorthands or patterns to be matched for custom divisors.

usual_divisor

Numeric. The default divisor applied to most combinations (e.g., 5).

custom_divisor

Numeric. The adjustment divisor for specified matches (e.g., 1).

Value

A data frame where rows represent habitats and columns represent ecosystem services, containing the divisor values for each intersection.


Ecosystem Service Importance Scores (between-service-type)

Description

A set of scores denoting the importance of each type group of ecosystem services to Scotland.

Usage

ns_between_importance_scores

Format

A named list of scores where values range from 0 to 20, representing the relative importance of each ecosystem service type. Item names are ecosystem service types.


Condition Indicator Relevance Matrix List

Description

A set of matrices recording whether or not each condition indicator is relevant to each habitat/ecosystem service combination.

Usage

ns_ci_relevance_matrices

Format

A named list of data frames:


Condition Indicator Score Matrix

Description

A matrix containing the raw condition indicator scores over the years of the time series.

Usage

ns_ci_scores

Format

A data frame:


Nature Scot Custom Divisor Matrix

Description

A matrix containing numbers by which the Ecosystem Service Potential per Unit Scores will be divided to calculate a weight.

Usage

ns_custom_divisor_matrix

Format

A data frame:


Display names of Condition Indicators

Description

Display name (no string cleaning) list of condition indicator names which is used internally.

Usage

ns_display_ci_names

Format

A character vector where items are the original number and name of NatureScot's 38 condition indicators:


Display name version of Ecosystem Services Label Tree

Description

Display name version (no string cleaning) version of ns_es_label_tree which is used internally.

Usage

ns_display_es_label_tree

Format

A named list of character vectors:


Display name version of Habitats Label Tree

Description

Display name version (no string cleaning) version of ns_habitats_label_tree which is used internally.

Usage

ns_display_habitats_label_tree

Format

A named list of character vectors:


Ecosystem Services Label Tree

Description

A hierarchical tree mapping ecosystem service types to specific ecosystem services.

Usage

ns_es_label_tree

Format

A named list of character vectors:


Habitat Extent for Scotland

Description

A table containing the annual extent (area) of various habitats.

Usage

ns_habitat_extent

Format

A data frame:


Habitats Label Tree

Description

A hierarchical tree mapping broad habitat groups to specific habitat types.

Usage

ns_habitats_label_tree

Format

A named list of character vectors:


Indicator Directory

Description

A table recording the salience of habitat condition scores as indicators of the likely flow of services under each ecosystem service type.

Usage

ns_indicator_directory

Format

A data frame with the following columns:


Provision Per Unit Scores

Description

A matrix of scores denoting the exemplary capacity of each habitat to provide each ecosystem service.

Usage

ns_provision_per_unit_scores

Format

A data frame:


Ecosystem Service Importance Scores (within-service-type)

Description

Sets of scores denoting the importance of each ecosystem service to Scotland, within its type group.

Usage

ns_within_importance_scores

Format

A named list of named lists of scores:


Year List

Description

A list of years for which data is available and over which the index will be calculated.

Usage

ns_year_list

Format

A character vector of year labels (e.g., "2000", "2001").


Prepare a blank data frame based on Habitat and ES trees

Description

Prepare a blank data frame based on Habitat and ES trees

Usage

prepare_template_matrix(hab_tree, es_tree)

Read and Process a Populated NCAI Template

Description

Imports data from an Excel workbook created by create_ncai_template. The function uses the provided label trees to re-align the data and applies automated cleaning to headers to ensure compatibility with internal openNCAI calculation engines. Note that the habitat and ecosystem service label trees should match the labels used in the spreadsheet; typically the same label trees should be used to generate and read the template.

Usage

read_ncai_template(path, habitats_label_tree, es_label_tree, ci_names)

Arguments

path

String. The file path to the populated .xlsx file.

habitats_label_tree

A named list of character vectors representing the habitat hierarchy. Names: broad habitats, typically EUNIS level 1. Character vector items: typically EUNIS level 2 habitats.

es_label_tree

A named list of character vectors representing the ecosystem service hierarchy. Names: typically SEEA ecosystem service types. Character vector items: typically CICES-type ecosystem services.

ci_names

The original character vector of indicator names used to create the template.

Value

A named list of data structures ready for use in get_ncai:

Examples


# 1. Define the trees (same as used in create_ncai_template)
habitat_label_tree <- list(
  'B. Coastal Habitats' = c("Coastal vegetated shingle", "Coastal dunes"),
  'E. Grasslands' = c("Dry Grasslands", "Mesic Grasslands")
)

ecosystem_service_label_tree <- list(
  'PROVISIONING' = c("1.1 Cultivated Crops"),
  'CULTURAL' = c("3.5. Existence & bequest")
)

condition_indicator_list <- c("National Water Quality Index")

# 2. Create a temporary template to read back in
# This ensures the example is self-contained and runnable.
tmp_path <- tempfile(fileext = ".xlsx")

create_ncai_template(
  template_out = tmp_path,
  habitats_label_tree = habitat_label_tree,
  es_label_tree = ecosystem_service_label_tree,
  ci_names = condition_indicator_list,
  year_list = 2024:2025
)

# 3. Read the template
# Even though it's empty, the function will process the headers and structure.
ncai_data <- read_ncai_template(
  path = tmp_path,
  habitats_label_tree = habitat_label_tree,
  es_label_tree = ecosystem_service_label_tree,
  ci_names = condition_indicator_list
)

# 4. Access the cleaned data structures
# Show the first few rows of the imported habitat extent matrix
head(ncai_data$habitat_extent)


Read and Label a Specific Yearly Asset Sheet

Description

Read and Label a Specific Yearly Asset Sheet

Usage

read_ns_year_sheet(sheet, path, es_label_tree, habitats_label_tree)

Arguments

sheet

The index or name of the Excel sheet to read.

path

String file path to the .xlsx source.

es_label_tree

Named list of ES labels.

habitats_label_tree

Named list of habitat labels.

Value

A labeled data frame representing the asset matrix for a single year.


Read Yearly Condition Indicator Scores

Description

Read Yearly Condition Indicator Scores

Usage

read_the_ci_scores(path, sheet_list, vector_range, ci_ids)

Arguments

path

Path to Excel source.

sheet_list

Vector of sheet indices.

vector_range

Range for the single-column score vectors.

ci_ids

Vector of indicator IDs.


Read Index and Breakdown Results

Description

Extracts the final index values (total, raw index, and smoothed index) for specific breakdowns (e.g., by habitat or service type) from the results sheet.

Usage

read_the_indices(indices_range, path, sheet, year_list)

Arguments

indices_range

A string representing the Excel range (e.g., "B2:D24").

path

String file path to the .xlsx source.

sheet

The index or name of the sheet containing the index summaries (usually 73).

Value

A data frame with years as row names and columns for raw total, raw index, and smoothed index.


Write Condition Scores Time-Series Sheet

Description

Write Condition Scores Time-Series Sheet

Usage

write_condition_scores_sheet(
  wb,
  sheet_name,
  ci_names,
  years,
  source_data = NULL
)

Write Habitat Extent Time-Series Sheet

Description

Write Habitat Extent Time-Series Sheet

Usage

write_extent_sheet(
  wb,
  sheet_name,
  hab_tree,
  years,
  hab_palette,
  source_data = NULL
)

Write the specialized Importance Weights sheet

Description

Write the specialized Importance Weights sheet

Usage

write_importance_sheet_with_data(
  wb,
  sheet_name,
  es_tree,
  between_data,
  within_list,
  instruction_style,
  entry_style
)

Write Indicator Directory Sheet

Description

Write Indicator Directory Sheet

Usage

write_indicator_directory(
  wb,
  sheet_name,
  ci_names,
  es_types,
  source_data = NULL
)

Write standard Matrix sheets (e.g., ES Potential or CI Relevance)

Description

Write standard Matrix sheets (e.g., ES Potential or CI Relevance)

Usage

write_input_matrix(
  wb,
  sheet_name,
  data_df,
  hab_tree,
  es_tree,
  style_obj,
  hab_palette,
  thick_border_style,
  instruction_style,
  instruction
)

Write a clean Instructions sheet at the start of the workbook

Description

Write a clean Instructions sheet at the start of the workbook

Usage

write_instructions_sheet(wb, sheet_name)