levels()
get_help()
docs
The levels()
function comes with R
and is part of the Base R
{base}
package.
We use this function to find the levels, aka ordered categories, of a factor variable. Any NA
values will be ignored and will not be considered separate levels. If the provided value is not a factor type, the result will be NULL
.
levels(factor variable)
The examples below use the carnivores
dataset. Learn more about this dataset with get_help("carnivores")
.
# Show the carnivores dataset
carnivores
## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <dbl> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Define a factor for the example from the character variable `carnivores$genus`
<- as.factor(carnivores$genus)
my_factor
# Show levels (ordered categories) of the factor variable:
levels(my_factor)
## [1] "Acinonyx" "Callorhinus" "Canis" "Haliochoerus" "Panthera" "Vulpes"
# Trying to find the levels of a non-factor results in NULL
# carnivores$genus is a character column
levels(carnivores$genus)
## [1] "Acinonyx" "Callorhinus" "Canis" "Haliochoerus" "Panthera" "Vulpes"