File: as_factor.R

package info (click to toggle)
r-cran-forcats 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 900 kB
  • sloc: makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,354 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#' Convert input to a factor
#'
#' Compared to base R, when `x` is a character, this function creates
#' levels in the order in which they appear, which will be the same on every
#' platform. (Base R sorts in the current locale which can vary from place
#' to place.) When `x` is numeric, the ordering is based on the numeric
#' value and consistent with base R.
#'
#' This is a generic function.
#'
#' @param x Object to coerce to a factor.
#' @param ... Other arguments passed down to method.
#' @export
#' @examples
#' # Character object
#' x <- c("a", "z", "g")
#' as_factor(x)
#' as.factor(x)
#'
#' # Character object containing numbers
#' y <- c("1.1", "11", "2.2", "22")
#' as_factor(y)
#' as.factor(y)
#'
#' # Numeric object
#' z <- as.numeric(y)
#' as_factor(z)
#' as.factor(z)
as_factor <- function(x, ...) {
  check_dots_used()
  UseMethod("as_factor")
}

#' @rdname as_factor
#' @export
as_factor.factor <- function(x, ...) {
  x
}

#' @rdname as_factor
#' @export
as_factor.character <- function(x, ...) {
  # Preserve label for future haven compatibility
  structure(
    fct_inorder(x),
    label = attr(x, "label", exact = TRUE)
  )
}

#' @rdname as_factor
#' @export
as_factor.numeric <- function(x, ...) {
  factor(x)
}

#' @rdname as_factor
#' @export
as_factor.logical <- function(x, ...) {
  factor(x, levels = c("FALSE", "TRUE"))
}