R/build_soil_input.R

Defines functions build_soil_input

Documented in build_soil_input

#' @title Build a soil inputs dataframe for the model
#' @description Takes any number of \code{add_*()} outputs as arguments. Calculates total organic
#' matter, carbon, nitrogen and lignin inputs in tonnes ha^-1, as well as nitrogen and lignin
#' fractions, and returns the results in a tibble with correct variable names to match the default
#' arguments of \code{run_model()}.
#' @param ... An object output by \code{add_crop()} or \code{add_manure}.
#' @importFrom purrr map map_int reduce
#' @export
build_soil_input <- function(...) {

  # list up args and map S3 method across
  inputs <- list(...)
  inputs <- map(inputs, soil_inputs)

  # check --- all vectors should be of the same length
  # pad with zeros + warn if needed
  vector_lengths <- unique(map_int(inputs, ~length(.x$om_input)))
  if (length(vector_lengths) > 1) {
    warning("Supplied input vectors are of different lengths. Shorter inputs will be padded with zero values.") # nolint
    inputs <- map(inputs, ~map(.x, ~c(.x, rep(0, max(vector_lengths) - length(.x)))))
  }

  # get totals, tibble up and work out fractions
  output <- tibble(
    om_input = map(inputs, ~.x$om_input) %>% reduce(`+`),
    c_input = map(inputs, ~.x$c_input) %>% reduce(`+`),
    n_input = map(inputs, ~.x$n_input) %>% reduce(`+`),
    lignin_input = map(inputs, ~.x$lignin_input) %>% reduce(`+`)
  ) %>%
    mutate(
      n_frac = .data$n_input / .data$om_input,
      lignin_frac = .data$lignin_input / .data$om_input
    )

  return(output)
}
aj-sykes92/soilc.ipcc documentation built on March 19, 2021, 11:52 a.m.