Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 41 / 68

factor, R's equivalent of an enum

This lesson covers using R's factor as the equivalent of an enum, with the aim of handling a fixed set of options clearly.

R has no enum syntax as other languages do, but factor() represents data restricted to a fixed set of options (levels). Use it when you want to limit the possible values in advance — a traffic light is only ever red, green, or amber.

The sample code builds a factor holding one of three options with factor("red", levels = c("red", "green", "blue")). Note that levels() lists every option that was defined.

A common early stumble is that a factor is a special type, not just a string. In statistical work a factor is treated specially as categorical data, and the ordering of its levels is managed too.

In professional work, factors are used widely in data analysis for fixed sets of options — survey response categories, experimental conditions.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)