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 characterH
has the index position or index number of1
, the second charactere
has the index2
, and so on.
# 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
Height
having 3
levels but 4
items.1
) of the factor from Tall
to Short
by referring to its index position using square brackets []
.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.
# 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
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.