R - Factor and Levels


#create a vector with eye colors of 8 persons
eyecolor <- c("black", "brown", "black", "green", "brown", "blue", "green", "blue")
eyecolor_factor <- factor(eyecolor)

eyecolor_factor         #prints the values with levels
levels(eyecolor_factor) #prints only the levels


[1] black brown black green brown blue  green blue 
Levels: black blue brown green
[1] "black" "blue"  "brown" "green"
Unordered Factors
#In the above example, we cannot compare the factors since they are unordered
eyecolor_factor[1] > eyecolor_factor[2]

[1] NA
Warning message:
In Ops.factor(eyecolor_factor[1], eyecolor_factor[2]) :
  ‘>’ not meaningful for factors
Ordered Factors

#Create a vector with different ratings
rating <- c("poor","bad","excellent","average","good","excellent")
rating_factor <- factor(rating, ordered=TRUE,
                        levels = c("bad","poor","average","good","excellent"))
rating_factor                        #prints with varying levels
rating_factor[1] > rating_factor[2]  #compare them
[1] excellent good      average   bad       poor     
Levels: bad < poor < average < good < excellent
[1] TRUE

No comments:

Post a Comment