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