Allows conversion of factor to numeric values preserving original levels
Source:R/as_factor.R
fct2num.Rd
Allows conversion of factor to numeric values preserving original levels
Examples
c(1, 4, 3, "A", 7, 8, 1) |>
as_factor() |>
fct2num()
#> Warning: invalid roman numeral: A
#> [1] 1 2 3 4 5 6 1
structure(c(1, 2, 3, 2, 10, 9),
labels = c(Unknown = 9, Refused = 10),
class = "haven_labelled"
) |>
as_factor() |>
fct2num()
#> [1] 1 2 3 2 10 9
structure(c(1, 2, 3, 2, 10, 9),
labels = c(Unknown = 9, Refused = 10),
class = "labelled"
) |>
as_factor() |>
fct2num()
#> [1] 1 2 3 2 10 9
# Outlier with labels, but no class of origin, handled like numeric vector
# structure(c(1, 2, 3, 2, 10, 9),
# labels = c(Unknown = 9, Refused = 10)
# ) |>
# as_factor() |>
# fct2num()
v <- sample(6:19,20,TRUE) |> factor()
dput(v)
#> structure(c(10L, 9L, 3L, 2L, 6L, 9L, 3L, 5L, 4L, 9L, 1L, 6L,
#> 5L, 5L, 3L, 8L, 2L, 7L, 1L, 11L), levels = c("6", "7", "8", "9",
#> "11", "12", "13", "14", "15", "16", "17"), class = "factor")
named_levels(v)
#> 16 15 8 7 12 11 9 6 14 13 17
#> 10 9 3 2 6 5 4 1 8 7 11
fct2num(v)
#> [1] 16 15 8 7 12 15 8 11 9 15 6 12 11 11 8 14 7 13 6 17