How to Add New Level to Factor in R (With Example)


You can use the following basic syntax to add a new level to a factor variable in R:

levels(df$my_factor) <- c(levels(df$my_factor), 'new_level')

The following example shows how to use this syntax in practice.

Example: Add New Level to Factor in R

Suppose we have the following data frame in R that shows the number of sales made in different regions for some retail store:

#create data frame
df <- data.frame(region=factor(c('A', 'B', NA, 'D', NA, 'F')),
                 sales=c(12, 18, 21, 14, 34, 40))

#view data frame
df

  region sales
1      A    12
2      B    18
3   <NA>    21
4      D    14
5   <NA>    34
6      F    40

Notice that the region variable is a factor.

To view the levels for this factor, we can use the levels() function:

#view factor levels for region
levels(df$region)

[1] "A" "B" "D" "F"

We can use the following syntax to add a new factor level called “no region”:

#add factor level called 'no region'
levels(df$region) <- c(levels(df$region), 'no region')

#convert each NA to 'no region'
df$region[is.na(df$region)] <- 'no region'

#view factor levels for region
levels(df$region)

[1] "A" "B" "D" "F" "no region"

The new level called “no region” has been added as a factor level.

If we’d like, we can use the table() function to count the occurrence of each factor level:

#view occurrences of each factor level
table(df$region)

A         B         D         F no region 
1         1         1         1         2 

From the output we can see that the new factor level called “no region” occurs twice in the region column of the data frame.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Convert Factor to Numeric in R
How to Convert Factor to Character in R
How to Reorder Factor Levels in R

2 Replies to “How to Add New Level to Factor in R (With Example)”

  1. I tried this in R.4.4.1 using Rstudio. but table(df$region) gives:
    A B D F no region
    1 1 1 1 0
    see full script here
    levels(DF$region) DF
    region sales
    1 A 12
    2 B 18
    3 21
    4 D 14
    5 34
    6 F 40
    > levels(DF$region)
    [1] “A” “B” “D” “F” “no region”
    > table(DF$region)

    A B D F no region
    1 1 1 1 0

    is it because of a version update ? how to repeat this example in the new version?

    1. Hi h…The issue you’re encountering is likely related to how the factors (categorical variables) are being handled in your data frame. In R, when you create a factor, it assigns levels to the factor based on the unique values present in the data, and any missing or blank values are often not included unless explicitly specified.

      In your script, it seems that you have a factor with levels “A”, “B”, “D”, “F”, and “no region,” but some rows have missing or empty values in the `region` column. The table function counts the occurrences of each level in the factor, but it doesn’t count missing or NA values unless they are explicitly handled.

      Here’s how you can address this:

      1. **Convert Empty Strings to a Specific Level:** If you want the empty strings (e.g., rows 3 and 5) to be counted as “no region,” you can explicitly set them before creating the factor.

      2. **Example Code to Handle This:**

      “`r
      # Sample Data
      DF <- data.frame( region = c("A", "B", "", "D", "", "F"), sales = c(12, 18, 21, 14, 34, 40) ) # Replace empty strings with "no region" DF$region <- ifelse(DF$region == "", "no region", DF$region) # Convert to factor DF$region <- factor(DF$region, levels = c("A", "B", "D", "F", "no region")) # Display the levels levels(DF$region) # Create a table of counts table(DF$region) ``` 3. **Explanation:** - The `ifelse` function replaces any empty strings in the `region` column with "no region." - The `factor` function creates a factor with specified levels, ensuring that "no region" is included as a level. - The `table` function then counts the occurrences of each level, including "no region." 4. **Expected Output:** ```r A B D F no region 1 1 1 1 2 ``` This approach should give you the correct count of regions, including those labeled as "no region."

Leave a Reply

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