Skip to contents

Allows conversion of factor to numeric values preserving original levels

Usage

fct2num(data)

Arguments

data

vector

Value

numeric vector

Examples

c(1, 4, 3, "A", 7, 8, 1) |>
  as_factor() |>
  fct2num()
#> [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(7L, 1L, 10L, 3L, 10L, 10L, 9L, 8L, 3L, 2L, 6L, 8L, 
#> 3L, 5L, 4L, 8L, 1L, 6L, 5L, 5L), levels = c("6", "7", "8", "9", 
#> "11", "12", "13", "15", "16", "17"), class = "factor")
named_levels(v)
#> 13  6 17  8 16 15  7 12 11  9 
#>  7  1 10  3  9  8  2  6  5  4 
fct2num(v)
#>  [1] 13  6 17  8 17 17 16 15  8  7 12 15  8 11  9 15  6 12 11 11