R/replace_backtraced.R

#' Replace chains of values
#'
#' `replace_backtraced` replaces chains of backtraced values within a vector.
#'
#' Simple convenience function that replaces all entries in a vector `x` for
#' which a matching vector `backtrace` contains `1`. Intended for use with
#' `backtrace_values()`.
#'
#' @param  x A vector in which a values are to be replaced.
#' @param backtrace An integer vector of the same length as `x`, with values
#'   of `1` if the entry belongs to a chain, and `0` otherwise. As
#'   returned by `backtrace_values()`.
#' @param replace_val New value for all entries belonging to a chain of backtraced
#'   values.
#' @return A copy of vector `x` in which all elements that belong to a chain have
#'   been replaced by the value `replace`.
#' @examples
#' # A sequence of mortality assessments containing erroneous instances of "Dead"
#' x <- c("Alive", "Almost dead", "Dead", "Dead", "Dead", "Alive", "Dead",
#'             "Dead", "Alive", "Dead", "Cut and Resprout", "Dead", "Alive")
#' da_starts <- detect_transitions(x, c("Dead", "Alive"))
#' da_trace <- backtrace_values(x, "Dead", da_starts)
#'
#' # Set erroneous entries to "Alive"
#' replace_backtraced(x, da_trace, "Alive")
#' @export
replace_backtraced <- function(x, backtrace, replace_val) {

    if(length(x) != length(backtrace)) {
        stop("`x` and `backtrace` must be vectors of the same length.")
    }
    if(length(replace_val) != 1) {
        stop("`replace_val` must be a vector of length 1.")
    }

    x[as.logical(backtrace)] <- replace_val
    return(x)
}
dschoenig/IDENTcc documentation built on May 16, 2019, 4:07 a.m.