How to change the item value of a factor in R
Overview
A factor in R is used to categorize data. The corresponding values in a factor are referred to as items of the factor.
The value of an item of a factor can be changed by referring to its index number in the factor using square brackets [].
It is worth noting that the first character of any object in R has an index position of
1. For example, in the string"Hello", the first characterHhas the index position or index number of1, the second characterehas the index2, and so on.
Code example
# creating a factorHeight <- factor(c("Tall", "Average", "Short", "Average"))# changing the first item of the factorHeight[1] <- "Short"# accessing the firt item of the factorHeight
Code explanation
- Line 2: We create a factor object
Heighthaving3levels but4items. - Line 5: We change the first item (index
1) of the factor fromTalltoShortby referring to its index position using square brackets[]. - Line 8: We print the modified factor object
Height.
It is worth noting that we cannot change the value of a specific item if it does not exist or is not specified in the existing factor. Trying to do so will return an error, like in the example below.
Code example
# creating a factorHeight <- factor(c("Tall", "Average", "Short", "Average"))# changing the first item of the factorHeight[1] <- "Giant"# accessing the first item of the factorHeight
Code explanation
The output of the code above reads:
Warning message:
In `[<-.factor`(`*tmp*`, 1, value = "Giant") :
invalid factor level, NA generated
This is so because the value Giant was not specified already in the existing factor.
This will work only if we specify that item in the factor, as we did in the first code example.