R/spec_helpers.R

Defines functions expand_seed_mixtures resolve_aliases product_flag device_flag

#' Behaviour flag of devices
#'
#' Looks up a behaviour flag of devices in the internal data generated from
#'  `inst/spec/devices.json` (see `tools/build-specifications.R`).
#'
#' @param device character vector of devices
#' @param flag name of the flag, one of "terminates_main_crop",
#'  "terminates_cover_crop", "stir_not_applicable"
#' @param default value used for devices without an explicit flag
#'  (recycled to the length of `device`)
#'
#' @return logical vector
#'
#' @md
#' @noRd
device_flag <- function(device, flag, default) {
  value <- spec_device_flags[[flag]][match(device, spec_device_flags$device)]
  default <- rep_len(default, length(device))
  ifelse(is.na(value), default, value)
}

#' Behaviour flag of products
#'
#' @param product character vector of products
#' @param flag name of the flag, e.g. "terminates_vegetation"
#'
#' @return logical vector, FALSE for products without the flag
#'
#' @md
#' @noRd
product_flag <- function(product, flag) {
  value <- spec_product_flags[[flag]][match(product, spec_product_flags$product)]
  !is.na(value) & value
}

#' Replace aliases by their identifiers
#'
#' @param values character vector
#' @param attribute attribute the values belong to, e.g. "crop" or "device"
#'
#' @return character vector with aliases replaced
#'
#' @md
#' @noRd
resolve_aliases <- function(values, attribute) {
  aliases <- spec_aliases[spec_aliases$attribute == attribute, ]
  i <- match(values, aliases$alias)
  ifelse(is.na(i), values, aliases$id[i])
}

#' Expand seed mixtures into their components
#'
#' Replaces each record whose `product` is a seed mixture of
#'  `inst/spec/seed_mixtures.json` by one record per component, with the
#'  component crop as `product`. Other records are kept as they are.
#'
#' @param data a data frame with the column `product`
#'
#' @return data frame with the mixtures expanded
#'
#' @md
#' @noRd
expand_seed_mixtures <- function(data) {
  mixtures <- spec_seed_mixtures
  if (nrow(data) == 0 || !any(data$product %in% mixtures$mixture)) return(data)
  components <- lapply(data$product, function(p) {
    m <- which(mixtures$mixture == p)
    if (length(m) == 0) NA_integer_ else m
  })
  out <- data[rep(seq_len(nrow(data)), lengths(components)), , drop = FALSE]
  component <- unlist(components)
  out$product[!is.na(component)] <- mixtures$crop[component[!is.na(component)]]
  out
}

Try the SoilManageR package in your browser

Any scripts or data that you put into this service are public.

SoilManageR documentation built on Nov. 17, 2026, 5:08 p.m.