Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I have a data frame containing a factor. When I create a subset of this data frame using subset() or another indexing function, a new data frame is created. However, the factor variable retains all of its original levels -- even when they do not exist in the new data frame.

This creates headaches when doing faceted plotting or using functions that rely on factor levels.

What is the most succinct way to remove levels from a factor in my new data frame?

Here's my example:

df <- data.frame(letters=letters[1:5],

                    numbers=seq(1:5))

levels(df$letters)

## [1] "a" "b" "c" "d" "e"

subdf <- subset(df, numbers <= 3)

##   letters numbers

## 1       a       1

## 2      b       2

## 3      c       3    

## but the levels are still there!

levels(subdf$letters)

## [1] "a" "b" "c" "d" "e"

1 Answer

0 votes
by

To drop levels that do not occur in a subset data frame, use the factor() function as follows:

subdf$letters <- factor(subdf$letters)

subdf$letters

Output:

[1] a b c

Levels: a b c

You can also use the droplevels() function as follows:

subdf <- df %>% filter(numbers <= 3) %>% droplevels()

subdf$letters

Output:

[1] a b c

Levels: a b c

 

Browse Categories

...