Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R levels() Function - Factor Level Operations

R levels() Function - Factor Level Operations

R Language Examples R Language Examples

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:

Example

Create a 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

(

"Count of each blood type:"

)

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 (by rebuilding the factor)

result

<-

factor

(

blood_type,

                 

levels

=

c

(

"Type O"

,

"Type A"

,

"Type B"

,

"Type AB"

)

)

print

(

"In order:"

)

print

(

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 R Language Examples