R/convert_to_written.R

#' Convert to written
#'
#' Converts a character vector to a written format, separated by commas and
#' the word "and".
#'
#' @param vec_in vector to input
#' @author Andrew Pfeiffer <andrew.j.pfeiffer@@gmail.com>
#' @importFrom stringr str_c
#' @importFrom stats na.omit
#' @export
#' @note 21 June 2017

convert_to_written <- function(vec_in){
    # Return error if class isn't character.
    if (!identical(class(vec_in), "character"))
       stop("Class must be character")

    # Remove NAs - they just make things annoying
    vec_1 <- stats::na.omit(vec_in)

    # Get length of vector - different results for lengths 0, 1 and 2+
    vec_len <- length(vec_1)

    # Return error for length-zero vectors
    if (identical(vec_len, 0L))
        stop("Character vector must contain non-NA elements")

    if (vec_len > 1) {
        # If length of vector is greater than one
        # First, create a copy to avoid in-place modification
        vec_2 <- vec_1
        # Then replace the second last element and omit the last element
        vec_2[vec_len - 1] <- stringr::str_c(
            vec_1[vec_len - 1], vec_1[vec_len], sep = " and "
        )
        vec_3 <- vec_2[-vec_len]
        # Finally, collapse the vector into a single string
        vec_out <- stringr::str_c(vec_3, collapse = ", ")
    } else
        # If length of vector is equal to one, return the input with NAs gone
        vec_out <- vec_1

    return(vec_out)
}
andrewjpfeiffer/rutilities documentation built on May 11, 2019, 6:26 p.m.