Exchange Elements of Factor Vector in R (2 Examples)

In this tutorial you’ll learn how to replace certain elements or entire levels of a factor in the R programming language.

Example Data

my_fac <- factor(c("X", "AA", "BB", "Y", "X", "Y"))  # Construct factor in R
my_fac                                               # Show factor in RStudio console
# [1] X  AA BB Y  X  Y 
# Levels: AA BB X Y

Example 1: Substitute Entire Factor Level

levels(my_fac)[levels(my_fac) == "X"] <- "FOO"       # Exchanging entire factor level
my_fac                                               # Show updated factor
# [1] FOO AA  BB  Y   FOO Y  
# Levels: AA BB FOO Y

Example 2: Substitute Specific Element of Factor

my_fac <- as.character(my_fac)                       # Converting factor to character
my_fac[6] <- "BAR"                                   # Replacing specific element of vector
my_fac <- as.factor(my_fac)                          # Converting character to factor
my_fac                                               # Show updated factor
# [1] FOO AA  BB  Y   FOO BAR
# Levels: AA BAR BB FOO Y

Further Resources & Related Tutorials

Please find some additional R programming tutorials on topics such as vectors, extracting data, matrices, and missing data in the following list.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top