R/label.R

Defines functions label

Documented in label

#' @title Manipulate labels (or factors)
#' @description
#' \code{label} assigns value labels to variables
#' @param x A vector
#' @param labels specify a character vector that correspond to the levels
#' @details
#' See the following details on assigning labels on different types of vector.
#'
#' \strong{Numeric or factor}
#' The order of the labels appearing is the same as output from
#' \code{\link{tab}} function.
#'
#' \strong{Character}
#' For character, the order of labels have to be specified by alphabetical order.
#'
#' \strong{Logical}
#' TRUE means 1 and FALSE 2 in a logical vector. Hence, levels shoud be corresponding
#' to the numeric representation of the vector.
#'
#' @seealso \code{\link{gen}}, \code{\link{egen}}
#' @keywords value label, label levels
#' @author Myo Minn Oo (Email: \email{dr.myominnoo@@gmail.com} |
#' Website: \url{https://myominnoo.github.io/})
#' @examples
#' str(infert)
#'
#' ## Example 1: Numeric vector
#' table(infert$case)
#' case <- label(infert$case, c("No", "Yes"))
#' table(case)
#'
#' ## Example 2: factor
#' table(infert$education)
#' edu <- label(infert$education, c("low", "middle", "high"))
#' table(edu)
#'
#' ## Example 3: character
#' sex <- rep(c("Male", "Female", NA), c(30, 60, 10))
#' sex; table(sex)
#' sex1 <- label(sex, c('f', 'm'))
#' sex1; table(sex1)
#' label(sex, c('f', 'm', 'missing'))
#'
#' ## Example 4: Logical
#' s <- sex == "Male"
#' s; table(s)
#' s1 <- label(s, c("male", "female"))
#' s1; table(s1)
#' label(s, c('male', 'female', 'missing'))

#' @export
label <- function(x, labels = NULL)
{
  if (is.null(labels)) {
    x <- factor(x)
  } else {
    if (any(is.na(unique(x))) & (length(unique(x)) == length(labels))) {
      exclude <- NULL
    } else {exclude <- NA}
    if (is.numeric(x) | is.character(x)) {
      x <- factor(x, labels = labels, exclude = exclude)
    } else if (is.factor(x)) {
      x <- factor(unclass(x), labels = labels, exclude = exclude)
    } else if (is.logical(x)) {
      x <- factor(2 - x, labels = labels, ordered = FALSE, exclude = exclude)
    } else stop('x can not be labelled.')
  }
  return(x)
}
myominnoo/stats2 documentation built on Nov. 4, 2019, 8:33 p.m.