Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Data Types and Structures

Factors: Categorical Data in R

Learn R factors for categorical data. Create them, control levels and order, count categories with table(), bin numbers with cut(), and avoid the as.numeric trap.

Some data is not really text and not really numbers but categories: shirt sizes, countries, survey answers like "agree" and "disagree", treatment groups in an experiment. R stores these in a special type called a factor. A factor remembers the complete set of allowed values (its levels), which lets statistical functions and charts treat the data correctly.

Factors confuse many newcomers, mostly because they look like text but behave like numbers underneath. This lesson explains how they work and how to avoid the common traps.

Creating a factor

R
sizes <- factor(c("small", "large", "medium", "small", "large"))
sizes
#> [1] small  large  medium small  large 
#> Levels: large medium small

levels(sizes)
#> [1] "large"  "medium" "small" 

nlevels(sizes)
#> [1] 3

Look at the last line: Levels: large medium small. By default R sorts levels alphabetically, which is rarely the order you want for sizes. Set the order yourself with the levels argument:

R
sizes <- factor(
  c("small", "large", "medium", "small", "large"),
  levels = c("small", "medium", "large")
)
sizes
#> [1] small  large  medium small  large 
#> Levels: small medium large

Any value not listed in levels becomes NA. That is a useful guard against typos.

How factors are stored

Under the hood a factor is a vector of integer codes plus a table of level labels:

R
as.integer(sizes)
#> [1] 1 3 2 1 3

Code 1 means "small", 2 means "medium", 3 means "large". Storing small integers instead of repeated strings also saves memory in large data sets.

The classic trap. When a factor's labels look like numbers, as.numeric() returns the codes, not the labels:

R
f <- factor(c("30", "10", "30"))
as.numeric(f)
#> [1] 2 1 2

as.numeric(as.character(f))
#> [1] 30 10 30

Always go through as.character() first.

Counting categories

table() counts how many times each level occurs, including levels with zero rows:

R
table(sizes)
#> sizes
#>  small medium  large 
#>      2      1      2 

summary(sizes) gives similar counts. Proportions come from prop.table(table(sizes)).

Ordered factors

Sometimes categories have a natural order: small < medium < large. Add ordered = TRUE so R knows comparisons make sense:

R
size_ord <- factor(
  c("small", "large", "medium", "small", "large"),
  levels = c("small", "medium", "large"),
  ordered = TRUE
)
size_ord
#> [1] small  large  medium small  large 
#> Levels: small < medium < large

size_ord >= "medium"
#> [1] FALSE  TRUE  TRUE FALSE  TRUE

max(size_ord)
#> [1] large
#> Levels: small < medium < large

For an ordinary (unordered) factor, < gives NA with a warning, because "small < large" has no meaning for categories such as colors. Ordered factors also make charts and models respect the sequence.

flowchart LR
    A["Text values<br/>'small', 'large'"] -->|factor| B["Codes + levels<br/>1, 3 + labels"]
    B -->|as.character| A
    B -->|"ordered = TRUE"| C["Ordered factor<br/>small < medium < large"]

Figure: a factor is integer codes with labels; ordering is optional.

Changing levels

Rename labels with levels():

R
f <- factor(c("m", "f", "f", "m"))
levels(f) <- c("female", "male")   # same alphabetical order as before: f, m
f
#> [1] male   female female male  
#> Levels: female male

Careful: assigning new names relabels in the existing order. Here the old levels were f, m (alphabetical), so f became female and m became male. If you assign names in the wrong order, you silently swap categories. For safer renaming use the forcats package, for example fct_recode().

Trying to add a value that is not a level fails softly:

R
f[2] <- "other"
#> Warning message:
#> In `[<-.factor`(`*tmp*`, 2, value = "other") :
#>   invalid factor level, NA generated

When some levels are no longer used (after filtering), droplevels() removes them, so they stop appearing in tables and charts.

Turning numbers into categories with cut()

cut() bins a numeric vector into intervals and returns a factor:

R
ages <- c(5, 15, 25)
cut(ages, breaks = c(0, 10, 20, 30), labels = c("low", "mid", "high"))
#> [1] low  mid  high
#> Levels: low mid high

By default intervals are closed on the right: (0,10] includes 10 but not 0. Use right = FALSE to flip that, and include.lowest = TRUE to include the lowest break. Without labels, the levels are named like (0,10].

Factors and strings in practice

Since R 4.0, reading text columns gives character vectors by default, not factors. Create factors on purpose, when you want the level set and order, for example before drawing a chart where bar order matters. In the tidyverse the forcats package offers helpers such as fct_reorder() and fct_infreq(), covered with plots in Visualization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the "levels" of a factor?

    Levels are the fixed list of categories the factor may contain.
  2. 2. In what order does factor() sort levels by default?

    Use the levels argument to control the order explicitly.
  3. 3. f <- factor(c("30", "10", "30")). How do you get the numbers 30, 10, 30 back?

    as.numeric(f) returns the internal codes. Convert to character first.
  4. 4. What do you add to make comparisons like < meaningful for a factor?

    An ordered factor knows its levels have a ranking.

Summary

  • A factor stores categories as integer codes with a fixed set of labelled levels.
  • Set the level order with levels =; add ordered = TRUE for ranked categories.
  • table() counts categories; droplevels() removes unused ones; cut() turns numbers into a factor.
  • Never use as.numeric() directly on a factor of numeric-looking labels.
  • Values outside the levels become NA.

Next: Matrices and Arrays