R Func Levels
# R levels() Function - Factor Level Operations
[ R Language Examples](#)
The 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 it can also modify category names or reorder them.
The syntax format of the levels() function is as follows:
levels(x) levels(x) <- value
**Parameter Description:**
* **x** Factor.
* **value** New level vector.
## Example
```r
# 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("Counts of Each Blood Type:")
print(table(blood_type))
# Modify Level Labels
levels(blood_type)<-c("AType", "BType", "ABType", "OType")
print("After Modifying Labels:")
print(blood_type)
# Reorder Levels (by recreating the factor)
result <-factor(blood_type,
levels=c("OType", "AType", "BType", "ABType"))
print("Sort in Order:")
print(table(result))
Executing the above code outputs the following result:
```r
"Blood Type Factor:" A B AB O A B O A Levels: A AB B O "Levels:" "A" "AB" "B" "O" "Counts of Each Blood Type:" A AB B O 3 1 2 2 "After Modifying Labels:" AType BType ABType OType AType BType OType ATypeLevels: AType BType ABType OType "Sort in Order:" OType AType BType ABType 2 3 2 1
[ R Language Examples](#)
YouTip