gss_cat (from forcats) is a sample of the General Social Survey. Several columns store categorical responses.
library(tidyverse)gss_cat
# A tibble: 21,483 × 9
year marital age race rincome partyid relig denom tvhours
<int> <fct> <int> <fct> <fct> <fct> <fct> <fct> <int>
1 2000 Never married 26 White $8000 to 9999 Ind,near … Prot… Sout… 12
2 2000 Divorced 48 White $8000 to 9999 Not str r… Prot… Bapt… NA
3 2000 Widowed 67 White Not applicable Independe… Prot… No d… 2
4 2000 Never married 39 White Not applicable Ind,near … Orth… Not … 4
5 2000 Divorced 25 White Not applicable Not str d… None Not … 1
6 2000 Married 25 White $20000 - 24999 Strong de… Prot… Sout… NA
7 2000 Never married 36 White $25000 or more Not str r… Chri… Not … 3
8 2000 Divorced 44 White $7000 to 7999 Ind,near … Prot… Luth… NA
9 2000 Married 44 White $25000 or more Not str d… Prot… Other 0
10 2000 Married 47 White $25000 or more Strong re… Prot… Sout… 3
# ℹ 21,473 more rows
What is a factor?
A factor stores categorical data as a set of predefined levels — the possible values a variable can take.
levels(gss_cat$rincome)
[1] "No answer" "Don't know" "Refused" "$25000 or more"
[5] "$20000 - 24999" "$15000 - 19999" "$10000 - 14999" "$8000 to 9999"
[9] "$7000 to 7999" "$6000 to 6999" "$5000 to 5999" "$4000 to 4999"
[13] "$3000 to 3999" "$1000 to 2999" "Lt $1000" "Not applicable"
Under the hood, R stores the values as integers and keeps a lookup table of level labels. This is what makes factors compact and orderable.
Why not just use character strings?
Character vectors sort alphabetically. Factors let you control the order directly, which matters for plots and tables.