# USECASE: Ask 10 kids to order 1: nuggets, 2: pizza, or 3: salad
food <- c(2, 2, 1, 2, 1, 2, 1, 1, 2, 2)
food
# ==============================================================================
# LESSON: We can turn this into a factor with the factor() function
food2 <- factor(food)
food
# ==============================================================================
# USECASE: We can quickly and easily count each level with table()
table(food2)
# ==============================================================================
# LESSON: We can let R know that level=3 is also possible by specifying levels
food3 <- factor(food, levels = c(1, 2, 3))
food3
table(food3)
# ==============================================================================
# LESSON: We can also give a label to each level so it is more readable
food4 <- factor(food, levels = c(1, 2, 3),
labels = c("nuggets", "pizza", "salad"))
food4
table(food4)
# ==============================================================================
# PITFALL: Don't confuse levels and labels
food5 <- factor(food, levels = c("nuggets", "pizza", "salad"),
labels = c(1, 2, 3))
food5 # full of <NA> because it can't find these levels
# ==============================================================================
# USECASE: You can also just store the levels as strings (like self-labels)
genre <- c("pop", "metal", "pop", "rock", "rap", "rap", "pop", "rock")
genre
genre2 <- factor(genre) # observed levels will be assigned alphabetically
genre2
table(genre2)