R levels() Function - Factor Level Operations
The R levels() function is used to get or set the levels (categories) of a factor.
levels() can be used to see which categories a factor contains, and can also modify category names or reorder them.
The syntax of the levels() function is as follows:
levels(x)
levels(x) <- value
Parameter Description:
-
x A factor.
-
value A vector of new levels.
Example
Create a factor
blood_type
<-
factor
(
c
(
"A"
,
"B"
,
"AB"
,
"O"
,
"A"
,
"B"
,
"O"
,
"A"
)
)
(
"Blood type factor:"
)
(
blood_type
)
(
"Levels:"
)
(
levels
(
blood_type
)
)
Frequency count
(
"Count of each blood type:"
)
(
table
(
blood_type
)
)
Modify level labels
levels
(
blood_type
)
<-
c
(
"Type A"
,
"Type B"
,
"Type AB"
,
"Type O"
)
(
"After modifying labels:"
)
(
blood_type
)
Reorder levels (by rebuilding the factor)
result
<-
factor
(
blood_type,
levels
=
c
(
"Type O"
,
"Type A"
,
"Type B"
,
"Type AB"
)
)
(
"In order:"
)
(
table
(
result
)
)
The output of the code above is:
[1] "血型因子:"
[1] A B AB O A B O A
Levels: A AB B O
[1] "水平:"
[1] "A" "AB" "B" "O"
[1] "各血型数量:"
A AB B O
3 1 2 2
[1] "修改标签后:"
[1] A型 B型 AB型 O型 A型 B型 O型 A型
Levels: A型 B型 AB型 O型
[1] "按序排列:"
O型 A型 B型 AB型
2 3 2 1
R Language Examples