ZetCode

R factors

last modified November 19, 2026

A categorical variable takes one value from a fixed set of categories, such as small, medium, and large, or yes, no, and maybe. R stores such a variable as a factor: a vector of integer codes plus a levels attribute that maps each code to a label. Factors control the order in which categories are printed and tabulated, and statistical functions treat them as groups rather than as numbers. This article shows how factors are created, ordered, relabelled, and used for binning.

Creating a factor

The function factor converts a character vector into a factor. Without further arguments it takes the distinct values, sorts them alphabetically, and uses that sorted vector as the levels. Printing the factor shows the labels and a separate line with the levels, and table counts how often each level appears.

creating.R
sizes <- c("small", "large", "medium", "small", "large")
sizes <- factor(sizes)
print(sizes)
cat("levels:", levels(sizes), "\n")
print(table(sizes))

The levels are large, medium, and small, in alphabetical order, and the counts are two large, one medium, and two small. The labels look like strings, but internally each one is an integer code. That is why a factor uses less memory than the corresponding character vector when the labels repeat.

$ Rscript creating.R
[1] small  large  medium small  large 
Levels: large medium small
levels: large medium small 
sizes
 large medium  small 
     2      1      2 

Levels and codes

levels returns the labels in their stored order, and nlevels returns how many there are. as.integer converts a factor to its codes. A code is the position of the label in the level vector, not a number derived from the label itself.

categories.R
sizes <- factor(c("small", "large", "medium"))
cat("nlevels:", nlevels(sizes), "\n")
print(levels(sizes))
cat("codes:", as.integer(sizes), "\n")

The labels are large, medium, and small, so small has code three, large has code one, and medium has code two. The codes are an implementation detail, but they explain both the compact storage and the conversion trap described below. A factor can have levels that no element uses, which is useful when several data sets must share one vocabulary.

$ Rscript categories.R
nlevels: 3 
[1] "large"  "medium" "small" 
codes: 3 1 2 

Setting the level order

The levels argument sets the order explicitly. The order controls the arrangement of the printed values, the columns of a table, and the reference group in a statistical model. For sizes the natural order is small, medium, large, which is not alphabetical.

ordering.R
sizes <- factor(c("small", "large", "medium", "small"),
                levels = c("small", "medium", "large"))
print(sizes)
print(levels(sizes))

The values keep their original positions, but the level line now reads small, medium, large. A value that is not listed in levels becomes NA, so the argument also acts as a filter against unexpected categories. Setting the levels is the first step before plotting or modelling categorical data.

$ Rscript ordering.R
[1] small  large  medium small 
Levels: small medium large
[1] "small"  "medium" "large" 

Ordered factors

An ordered factor records that the levels have a meaningful order, as in small, medium, large. It is created with ordered = TRUE, and its level line uses less-than signs. Comparisons between its elements then work, which is not true for an ordinary factor.

ordinal.R
sizes <- factor(c("small", "large", "medium", "small"),
                levels = c("small", "medium", "large"),
                ordered = TRUE)
print(sizes)
cat("small < large:", sizes[1] < sizes[2], "\n")

The comparison sizes[1] < sizes[2] asks whether small comes before large and returns true. An ordered factor is appropriate for grades, agreement scales, and size classes, where the distance between neighbouring levels may not be equal but the direction is clear. For unordered categories such as colours, leave the factor unordered.

$ Rscript ordinal.R
[1] small  large  medium small 
Levels: small < medium < large
small < large: TRUE 

Relabelling codes

The labels argument maps each level to a new label. It is useful when the data stores numeric codes that stand for categories, as in a survey where 1 means small, 2 means medium, and 3 means large. The codes stay the same; only their printed names change.

relabel.R
codes <- c(1, 2, 1, 3)
sizes <- factor(codes, levels = c(1, 2, 3),
                labels = c("small", "medium", "large"))
print(sizes)

The four observations become small, medium, small, and large. The mapping is positional: the first label belongs to the first level, the second to the second, and so on. A mismatch between the number of levels and the number of labels is an error, which protects against silently shifting the categories.

$ Rscript relabel.R
[1] small  medium small  large 
Levels: small medium large

The as.numeric trap

Converting a factor directly to a number returns its codes, not the text of its labels. If the labels themselves look like numbers, the result is misleading. The safe route is to convert to character first and then to numeric, so that the label is parsed rather than the code.

converting.R
codes <- factor(c("10", "20", "30"))
print(as.numeric(codes))
print(as.numeric(as.character(codes)))

The first result is 1, 2, 3 because those are the positions of the levels, not because the labels are 10, 20, and 30. The second result is the actual values. The same mistake appears when a column of numbers is imported as a factor by mistake; check class after reading a file, and fix the import rather than converting the factor afterwards.

$ Rscript converting.R
[1] 1 2 3
[1] 10 20 30

Dropping unused levels

Subsetting a factor keeps all of its levels, even those that no longer appear in the data. The function droplevels removes the unused ones, which keeps tables and plots from showing empty categories. This matters after filtering a data frame down to a few groups.

dropping.R
sizes <- factor(c("small", "large", "medium", "small"))
subset_sizes <- sizes[1:2]
print(subset_sizes)
print(droplevels(subset_sizes))

The subset contains only small and large, but its level line still lists medium. After droplevels the medium level is gone. The values and their order do not change; only the vocabulary of the factor shrinks.

$ Rscript dropping.R
[1] small large
Levels: large medium small
[1] small large
Levels: large small

Binning numeric data

cut turns a numeric vector into a factor by dividing the range into intervals. The argument breaks gives the interval boundaries, labels names the resulting bins, and right = FALSE makes each interval closed on the left and open on the right. The result is a factor, so table counts the bins.

bins.R
scores <- c(72, 85, 90, 66, 78)
grades <- cut(scores, breaks = c(0, 70, 80, 90, 100),
              labels = c("F", "C", "B", "A"),
              right = FALSE)
print(grades)
print(table(grades))

The score 72 falls in the interval from 70 to 80, which is labelled C, and 90 falls in the last interval, which is labelled A. The table counts one F, two C, one B, and one A. Without right = FALSE the intervals would be closed on the right, and a score of exactly 70 would move to the lower bin.

$ Rscript bins.R
[1] C B A F C
Levels: F C B A
grades
F C B A 
1 2 1 1 

A complete example

The next script summarises survey responses on an ordered scale. The levels are no, maybe, and yes, so the table reads in a natural order rather than alphabetically. The last line computes the share of yes answers by comparing the factor with one of its levels.

survey.R
responses <- factor(c("yes", "no", "yes", "maybe", "yes", "no"),
                    levels = c("no", "maybe", "yes"),
                    ordered = TRUE)
print(responses)
print(table(responses))
cat("positive share:", mean(responses == "yes"), "\n")

The table shows two no, one maybe, and three yes, and half of the responses are yes. The comparison responses == "yes" returns a logical vector, which mean turns into a proportion. Because the factor is ordered, the categories also support comparisons such as responses >= "maybe".

$ Rscript survey.R
[1] yes   no    yes   maybe yes   no   
Levels: no < maybe < yes
responses
   no maybe   yes 
    2     1     3 
positive share: 0.5 

Next steps

The data frames article later in the series stores factors as columns next to numeric and character columns, and the descriptive statistics article uses table and aggregate to summarise them. The base graphics article uses factors to label the categories of a bar chart, and the regression article treats them as indicator variables.

Source

An Introduction to R: factors

R documentation: factor

R documentation: cut

R documentation: table

In this article we have created factors, inspected their levels and integer codes, and set the level order explicitly. We made an ordered factor, relabelled numeric codes, avoided the as.numeric trap, and dropped unused levels. We also binned a numeric vector with cut and summarised an ordered survey scale. The series continues with data frames.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.