R/char2factor.R

Defines functions char2factor

Documented in char2factor

#' Convert a Character Vector Into a Factor
#'
#' I often need a factor with levels the unique values of a character vector
#' (for example: to prevent ggplot2 from sorting the character vector).
#' @param x A character vector.
#' @param levels The levels to use, see \code{\link{factor}}.
#' @return A factor.
#' @family vector functions
#' @export
#' @examples
#' x <- c("beech", "oak", "spruce", "fir")
#' char2factor(x)
char2factor <- function(x, levels = unique(x)) {
    res <- factor(x, levels = levels)
    return(res)
}

Try the fritools package in your browser

Any scripts or data that you put into this service are public.

fritools documentation built on June 8, 2025, 11:59 a.m.