Example on class "factor"
Post date: Jun 30, 2013 10:49:48 PM
Here is a short example:
# This code demonstrates how to use factor # First, let's show the survey results survey.result <- c("F", "F", "D", "A-", "A+", "B-", "B", "B", "C", "C-") # This is the order of the possible responses order.ascend <- c("F", "D", "C-", "C", "B-", "B", "B+", "A-", "A", "A+") # Now, let's make them into factor result <- factor(x=survey.result, levels=order.ascend, ordered=TRUE) # We can also change the element of the factor # > result # [1] F F D A- A+ B- B B C C- # Levels: F < D < C- < C < B- < B < B+ < A- < A < A+ result[3] <- "A" # And the result becomes: # > result # [1] F F A A- A+ B- B B C C- # Levels: F < D < C- < C < B- < B < B+ < A- < A < A+ # We can also remove the class label result.integer <- unclass(result) # Here is what you will get # > result.integer # [1] 1 1 9 8 10 5 6 6 4 3 # attr(,"levels") # [1] "F" "D" "C-" "C" "B-" "B" "B+" "A-" "A" "A+" # Of course, we can return the label to them class(result.integer) <- "factor" # We simply say, make the class to be "factor", and that's it!