R/run_in.R

Defines functions run_in

Documented in run_in

#' @title Run in the model dataset
#' @description Takes the model input dataframe and calculates an averaged run-in row based on the
#' number of years specified in \code{dur}. Returns the model input dataframe with the run-in row
#' appended to the top of the data. The variables indicated as \code{year} and \code{climdata} are
#' excluded from the run-in row.
#' @param data A tibble containing model input data. See \code{toy_input} for example; run
#' \code{?toy_input} for variable interpretation and units.
#' @param dur An integer value specifying the number of rows to enter into the run-in calculation.
#' Defaults to 10 years.
#' @param year A character string indicating the name of the variable containing the year input.
#' Defaults to "year".
#' @param climdata A character string indicating the name of the list column containing climate
#' data. Defaults to "climdata".
#' @import dplyr
#' @examples
#' run_in(soilc.ipcc::toy_input,
#'        dur = 10)
#' @export
run_in <- function(data, dur = 10, year = "year", climdata = "climdata") {

  # warn off if run-in duration is wacky
  if (dur < 0) warning("Run-in duration must be a postive integer")
  if (dur > nrow(data)) warning("Run-in duration cannot be longer than data.")

  # calculate run-in (single row df)
  run_in <- data %>%
    arrange(.data[[year]]) %>%
    slice(1:dur) %>%
    summarise_all(
      ~ifelse(is.numeric(.),
              mean(., na.rm = TRUE),
              .[1])
    )

  # remove year and climdata from run in
  run_in[[year]] <- NA
  run_in[[climdata]] <- NULL

  # add back to main data
  data <- bind_rows(run_in, data)

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