Error in R: factor level is duplicated (2 Examples)

In this R tutorial you’ll learn how to handle the “Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level is duplicated".

Example 1: Replicating the Error – factor level is duplicated

my_fac <- factor(1:3, levels = c(1, 1, 2))    # Duplicated factor levels
# Error in `levels<-`(`*tmp*`, value = as.character(levels)) : 
#   factor level [2] is duplicated

Example 2: Solving the Error – factor level is duplicated

my_fac <- factor(1:3, levels = 1:3)           # Unique factor levels
my_fac                                        # Display factor in RStudio console
# [1] 1 2 3
# Levels: 1 2 3

Further Resources & Related Articles

You may have a look at the following list of R programming tutorials. They illustrate topics such as data objects, coding errors, and factors.

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