11  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.

11.1 Introduction

In R, we represent categorical or qualitative data with the data type factor.

11.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" 

11.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"  

11.4 Specify Labels

Use the labels argument to attach shorter 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

11.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

To reorder, recode or lump rare levels, see the forcats package.

Key points

  • Factors represent categorical data with a set of levels.
  • Use levels() and nlevels() to inspect the categories.
  • Set levels and ordered = TRUE when categories have a natural order.
  • Use labels to choose display labels and is.ordered() to check ordering.

Next: Lists in R