15) Creating a Factor from a Vector with Levels and Ordering.

This Blog entry is from the Data Structures section in Learn R.

Some categorical data does also have a precedence whereby each of the categorical variables is somehow elevated from the previous one, while not necessarily being distributed in a statistical fashion.  A good example would be temperature.  Start by creating a Vector called Temps:

Temps <- c("High","Medium","Low","Low","Medium")
creating-a-factor-script-in-r-of-temps.png

Run the line of script to console:

temps-factor-created-in-r-console.png

Create a similar Vector, this time with the distinct values in the order of precidence:

TempsDistinctOrder <- c("Low","Medium","High")
temps-in-their-logical-order-r-script.png

Run the line of script to console:

temps-in-their-logical-order-written-out-to-r-console.png

Create the factor by bringing the two newly created Vectors trogether and specfying that ordering is to be observed:

TempsFactor <- factor(Temps,TempsDistinctOrder,ordered=TRUE)
logical-order-of-temps-created-as-a-factor-r-script.png

Run the line of script to console:

creating-a-factor-of-logical-order-written-out-in-r-console.png

Write the Factor to console by typing:

TempsFactor
a-script-in-r-to-validate-factor-logical-order.png

Run the line of script to console:

factor-in-logical-order-written-out-to-r-console.png

It can be seen that the Factor levels now have < chevrons which denote the precedence.  Low is less than Medium,  Medium is less than High.  Rather usefully it is possible to use a logical test condition to perform a logical test for only those values in the factor that exceed a given level,  for example type:

TempsFactor > "Low"
script-to-filter-a-factor-in-logical-order-in-r.png

Run the line of script to console:

results-in-r-console-of-filtering-a-factor-on-greater-logic.png

It can be seen that a Vector of logical operators has been returned that could further be used for selecting and sub setting.