#' Converts six digit fire year values to four digit integer years.
#'
#' Fire years are expressed as financial years with no delimiters.
#' This function converts a vector of such values into four
#' digit year values. For example, the input values \code{c(199192, 199900, 201011)}
#' are converted to \code{c(1991, 1999, 2010)}.
#'
#' @param fireyrs Input six digit fire year values. The data type can be
#' integer, numeric, character or factor as long as the values can be
#' interpreted as 6 digit values.
#'
#' @param check Whether to check the validity of all input values. In a valid
#' six digit fire year value the last two digits refer to the year following
#' that indicated by the first four digits. E.g. '199192' is valid but
#' '199193' is not. Invalid fire year values could indicate other data entry
#' problems.
#'
#' @return Integer year values extracted from the leading four digits of the
#' input fire year values.
#'
#' @examples
#' # input values as character strings
#' fyrs <- c("199192", "199900", "200506")
#' yrs <- getFireYear(fyrs)
#'
#' # same thing with inptu values as integers
#' fyrs <- c(199192, 199900, 200506)
#' yrs <- getFireYear(fyrs)
#'
#' # middle value is invalid and will generate
#' # an error
#' \dontrun{
#' fyrs <- c("199192", "199999", "200506")
#' yrs <- getFireYear(fyrs)
#' }
#'
#' @export
#'
getFireYear <- function(fireyrs, check=TRUE) {
if (is.double(fireyrs))
fireyrs <- as.character(as.integer(fireyrs))
else
fireyrs <- as.character(fireyrs)
ii <- stringr::str_length(fireyrs) == 6
if (!all(ii)) {
stop("One or more invalid fire year values\n",
sort(unique(fireyrs[!ii])))
}
yr <- as.integer( stringr::str_sub(fireyrs, 1, 4) )
if (check) {
yr2 <- stringr::str_sub(as.character(yr + 1), 3, 4)
matches <- yr2 == stringr::str_sub(fireyrs, 5, 6)
if (any(!matches)) {
stop("One or more invalid fire year strings:\n",
sort(unique(fireyrs[!matches])))
}
}
yr
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.