Convert Categorical Values to Numeric Improvement to seq_along()
Source:R/categorical_to_numeric.R
categorical_to_numeric.Rd
Converts categorical values into numeric by sorting unique values alphabetically/numerically and assigning sequential numbers starting from 1
Arguments
- x
A vector containing categorical values (character or factor)
- decreasing
logical. Should the sort be increasing or decreasing?
Value
A numeric vector where each category is mapped to a number based on its sorted position. NA values in the input remain NA in the output.
Examples
# Example 1: Basic character vector
fruits <- c("apple", "banana", "apple", "cherry", "banana")
cat_to_num(fruits, decreasing = FALSE) # Returns: 1, 2, 1, 3, 2
#> apple banana apple cherry banana
#> 1 2 1 3 2
# Example 2: Vector with NAs
grades <- c("A", NA, "C", "B", "A", NA)
cat_to_num(grades) # Returns: 1, NA, 3, 2, 1, NA
#> A <NA> C B A <NA>
#> 1 NA 3 2 1 NA
# Example 3: Factor input
animals <- factor(c("dog", "cat", "bird", "cat", "dog"))
cat_to_num(animals) # Returns: 3, 2, 1, 2, 3
#> dog cat bird cat dog
#> 3 2 1 2 3
# Example 4: Numeric categories
sizes <- c("XL", "S", "M", "XS", "L")
cat_to_num(sizes) # Returns: 5, 2, 3, 1, 4
#> XL S M XS L
#> 4 3 2 5 1
# Example 5: Single category
status <- c("active", "active", "active")
cat_to_num(status) # Returns: 1, 1, 1
#> active active active
#> 1 1 1
# Examples for cat_to_num2
# Assign numeric values to a set of categorical values
# Call the value assignment to assign
# a numeric value to a new categorical value
cat_to_num2(letters[1:7])("b")
#> [1] 2
cat_to_num2(letters[1:7], decreasing = FALSE)("d")
#> [1] 4
# the above assigns numeric values to letters a-g
# and then calls the number for "a"
cat_vals_5 <- c("apple","orange","guava")
num_equiv <- cat_to_num2(cat_vals_5)
applenum = num_equiv("apple")