Wednesday, April 24, 2019

r - Drop factor levels in a subsetted data frame



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




This causes problems 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 the new dataframe?



Here's an 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

# all levels are still there!

levels(subdf$letters)
## [1] "a" "b" "c" "d" "e"

Answer



All you should have to do is to apply factor() to your variable again after subsetting:



> subdf$letters
[1] a b c
Levels: a b c d e
subdf$letters <- factor(subdf$letters)

> subdf$letters
[1] a b c
Levels: a b c


EDIT



From the factor page example:



factor(ff)      # drops the levels that do not occur



For dropping levels from all factor columns in a dataframe, you can use:



subdf <- subset(df, numbers <= 3)
subdf[] <- lapply(subdf, function(x) if(is.factor(x)) factor(x) else x)

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...