Create a numeric index over the unique levels of a variable.

index_from_levels(v, levels = NULL)

Arguments

levels

An optional vector specifying the order for which numbers should be assigned to levels.

obj_vector

A vector that can be converted into a factor.

Value

An integer vector from 1 to the number of unique levels.

Examples

# Variable with 3 unique levels
v <- rep( LETTERS[3:1], each = 3 )

# Convert to numeric index
index_from_levels( v )
#> [1] 1 1 1 2 2 2 3 3 3

# Can control assignment of indices
index_from_levels( v, levels = LETTERS[1:3] )
#> [1] 3 3 3 2 2 2 1 1 1

# To combine over multiple variables use 'paste0'
v1 <- rep( LETTERS[1:2], each = 4 )
v2 <- rep( letters[1:2], 4 )
index_from_levels( paste0( v1, v2 ) )
#> [1] 1 2 1 2 3 4 3 4