R levels() Function - Factor Level Operations

R 语言实例R Language Example

R levels() function is used to get or set the levels (categories) of a factor.

levels() can be used to view which categories a factor contains, and also to modify category names or reorder them.

The syntax of the levels() function is as follows:

levels(x)
levels(x) <- value

Parameter description:

  • xFactor.

  • valueNew level vector.

Example

# Create factor
blood_type <- factor(c("A", "B", "AB", "O", "A", "B", "O", "A"))
print("Blood type factor:")
print(blood_type)
print("Levels:")
print(levels(blood_type))

# Frequency count
print("Blood type counts:")
print(table(blood_type))

# Modify level labels
levels(blood_type) <- c("Type A", "Type B", "Type AB", "Type O")
print("After modifying labels:")
print(blood_type)

# Reorder levels (rebuild via factor)
result <- factor(blood_type,
                 levels = c("Type O", "Type A", "Type B", "Type AB"))
print("In order:")
print(table(result))

The output of executing the above code 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 语言实例R Language Example

Other Extensions