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

R ProgrammingServer Side ProgrammingProgramming

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

 Live Demo

Consider the below data frame −

x1<−factor(sample(letters[1:3],20,replace=TRUE))
y1<−rnorm(20,5,0.31)
df1<−data.frame(x1,y1)
df1

Output

x1 y1
1 a 4.480255
2 b 4.865971
3 a 5.278760
4 a 5.208462
5 c 4.815111
6 a 5.116731
7 a 5.278687
8 b 5.832620
9 c 5.182383
10 a 4.741525
11 b 4.645954
12 c 4.972552
13 a 5.515956
14 c 4.951365
15 b 5.214277
16 c 5.444890
17 b 4.590310
18 a 4.949908
19 a 4.858476
20 c 5.179366

Extracting factor levels of x1 −

Example

levels(df1$x1)

Output

[1] "a" "b" "c"

Example2

 Live Demo

If the column values are not recorded as factor level but they represent them then we need to use as.factor with the column as shown in the below example −

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"
raja
Published on 09-Feb-2021 12:21:10
Advertisements