Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

factor
r
communitycreator

How to change the item value of a factor in R

Onyejiaku Theophilus Chidalu

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 character H has the index position or index number of 1, the second character e has the index 2, and so on.

Code example

# creating a factor
Height <- factor(c("Tall", "Average", "Short", "Average"))

# changing the first item of the factor
Height[1] <- "Short"

# accessing the firt item of the factor
Height
Changing the value of an item of a factor

Code explanation

  • Line 2: We create a factor object Height having 3 levels but 4 items.
  • Line 5: We change the first item (index 1) of the factor from Tall to Short by 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 factor
Height <- factor(c("Tall", "Average", "Short", "Average"))

# changing the first item of the factor
Height[1] <- "Giant"

# accessing the first item of the factor
Height
Creating an invalid factor level

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.

RELATED TAGS

factor
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring