To create factors in R, you can use the factor()
function. Factors are used to represent categorical data and can be ordered or unordered.
In this example,
colors
which contains the values 'red'
, 'green'
, 'blue'
, and 'green'
. This vector represents categorical data.factor()
function to convert the colors
vector into a factor. We assign the result to a variable named colors_factor
. The factor()
function interprets the unique values in the vector as different levels of the factor.colors_factor
to the console to see the factor levels and the data it contains. Each unique value in the original vector becomes a level of the factor.levels()
function to print the levels of the factor. This shows all the unique values that the factor can take.colors <- c('red', 'green', 'blue', 'green')
colors_factor <- factor(colors)
print(colors_factor)
print(levels(colors_factor))
[1] red green blue green Levels: blue green red [1] "blue" "green" "red"
In this example,
sizes
which contains the values 'small'
, 'large'
, 'medium'
, and 'small'
. This vector represents ordered categorical data.factor()
function to convert the sizes
vector into a factor, specifying the levels argument to define the order of levels: c('small', 'medium', 'large')
. We assign the result to a variable named sizes_factor
. The factor()
function with the levels
argument ensures that the factor levels have a specific order.sizes_factor
to the console to see the factor levels and the data it contains. The factor levels are now ordered according to the specified levels
argument.is.ordered()
function to check if the factor is ordered, and print the result. This confirms that the factor has an inherent order.sizes <- c('small', 'large', 'medium', 'small')
sizes_factor <- factor(sizes, levels = c('small', 'medium', 'large'), ordered = TRUE)
print(sizes_factor)
print(is.ordered(sizes_factor))
[1] small large medium small Levels: small < medium < large [1] TRUE
In this tutorial, we learned How to Create Factors in R language with well detailed examples.