How to extract the factor levels from factor column in an R data frame?

To extract the factor levels from factor column, we can simply use levels function. For example, if we have a data frame called df that contains a factor column defined with x then the levels of factor levels in x can be extracted by using the command levels(df$x). This extraction is helpful if we have a large number of levels.

Example1

x2<−sample(c("Hot","Cold","Warm"),20,replace=TRUE)
y2<−rpois(20,30)
df2<−data.frame(x2,y2)
df2

Output

x2 y2
1 Warm 29
2 Hot 23
3 Cold 26
4 Hot 30
5 Hot 36
6 Hot 25
7 Hot 34
8 Hot 24
9 Warm 29
10 Hot 34
11 Warm 25
12 Cold 26
13 Hot 30
14 Cold 31
15 Warm 28
16 Cold 25
17 Cold 32
18 Hot 25
19 Hot 32
20 Cold 28

Output

levels(df2$x2)

Output

NULL

Example

levels(factor(df2$x2))

Output

[1] "Cold" "Hot" "Warm"
Updated on: 2026-03-11T23:22:53+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements