8  Factors in R

Learning Objectives: After this chapter you will be able to:

  • Create a factor from a character vector.
  • Inspect and count levels with levels() and nlevels().
  • Impose a natural order with levels= together with ordered = TRUE.
  • Attach shorter display labels with labels=.
  • Test for ordering with is.ordered().
  • Reach for forcats when you need to recode, reorder, or lump levels.

8.1 Introduction

Categorical or qualitative data in R is treated as data type factor.

8.2 Create Factors

args(factor)
function (x = character(), levels, labels = levels, exclude = NA, 
    ordered = is.ordered(x), nmax = NA) 
NULL
devices <- factor(c('Mobile', 'Tablet', 'Desktop'))
devices
[1] Mobile  Tablet  Desktop
Levels: Desktop Mobile Tablet
# number of levels
nlevels(devices)
[1] 3
# levels
levels(devices)
[1] "Desktop" "Mobile"  "Tablet" 

8.3 Order Levels

Use the levels argument together with ordered = TRUE when the categories have a natural order:

size <- factor(c('Medium', 'Low', 'High', 'Low', 'Medium'),
  levels = c('Low', 'Medium', 'High'), ordered = TRUE)
size
[1] Medium Low    High   Low    Medium
Levels: Low < Medium < High
levels(size)
[1] "Low"    "Medium" "High"  

8.4 Specify Labels

Use the labels argument to attach shorter or prettier display labels while keeping the underlying level order:

size_labeled <- factor(c('Low', 'Medium', 'High'),
  levels = c('Low', 'Medium', 'High'), labels = c('L', 'M', 'H'))
size_labeled
[1] L M H
Levels: L M H

8.5 Check Levels

# existing levels
levels(size)
[1] "Low"    "Medium" "High"  
# number of levels
nlevels(size)
[1] 3
# is this an ordered factor?
is.ordered(size)
[1] TRUE

For modern factor manipulation (reordering, recoding, lumping rare levels), see the forcats package.