#' Detect value transitions
#'
#' `detect_transitions` detects transitions between values in a vector.
#'
#' This function is intended to be a helper function to quickly detect
#' transitions in a sequence of values that are assumed to be erroneous. The
#' output may be coerced to a logical vector and used for indexing the original
#' sequence (see examples).
#'
#' @param x A vector in which transitions are to be detected.
#' @param transition A vector of length 2, specifying the first and second value
#' of the transition.
#' @return An integer vector of the same length as `x`. The start (i.e. first
#' value) of a transition is `1` all other entries are `0`.
#' @examples
#' # Example for a sequence of values where a tree turns "Alive" after having
#' # been measured "Dead"
#' x <- c("Alive", "Almost dead", "Dead", "Dead", "Dead", "Alive", "Dead",
#' "Dead", "Alive", "Dead", "Cut and Resprout", "Dead", "Alive")
#' detect_transitions(x, c("Dead", "Alive"))
#'
#' # Extract starting points of the transition
#' trans <- as.logical(detect_transitions(x, c("Dead", "Alive")))
#' which(trans)
#' x[trans]
#' @export
detect_transitions <- function(x, transition) {
if(length(transition) != 2) {
stop("`transition` must be a vector of length 2.")
}
if(is.factor(x)) {
x <- as.character(x)
}
x1 <- x
x2 <- x
x1[x == transition[1]] <- 1
x1[x != transition[1]] <- 0
x2[x == transition[2]] <- 1
x2[x != transition[2]] <- 0
x_detected <- as.integer(x1) * as.integer(x2[c(2:length(x2), length(x2))])
return(x_detected)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.