570

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"
Henrik
  • 56,228
  • 12
  • 124
  • 139
medriscoll
  • 24,637
  • 16
  • 36
  • 36

15 Answers15

508

Since R version 2.12, there's a droplevels() function.

levels(droplevels(subdf$letters))
Roman Luštrik
  • 64,404
  • 24
  • 143
  • 187
  • 8
    An advantage of this method over using `factor()` is that it's not necessary to modify the original dataframe or create a new persistent dataframe. I can wrap `droplevels` around a subsetted dataframe and use it as the data argument to a lattice function, and groups will be handled correctly. – Mars Nov 21 '15 at 05:44
  • I've noticed that if I have an NA level in my factor (a genuine NA level), it is dropped by dropped levels, even if the NAs are present. – Meep Jul 05 '16 at 00:48
444

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)
hatmatrix
  • 36,897
  • 38
  • 126
  • 217
  • 22
    That's fine for a one-off, but in a data.frame with a large number of columns, you get to do that on every column that is a factor ... leading to the need for a function such as drop.levels() from gdata. – Dirk Eddelbuettel Jul 29 '09 at 14:16
  • 6
    I see... but from a user-perspective it's quick to write something like subdf[] – hatmatrix Jul 29 '09 at 17:09
  • 1
    Thanks Stephen & Dirk - I'm giving this one the thumbs up for the caes of one factor, but hopefully folks will read these comments for your suggestions on cleaning up an entire data frame of factors. – medriscoll Jul 30 '09 at 04:18
  • 9
    As a side-effect the function converts the data frame to a list, so the `mydf – Johan May 09 '14 at 10:41
  • What also might be noteworthy: `rlm` really goes wrong when your data.frame contains factors which contain levels with no data. You'll get an error: singular fits are not implemented in 'rlm' . Most of the time your matrix is not singular, it's just exactly this problem. – Matt Bannert Jun 19 '14 at 14:31
  • 1
    Also: this method _does_ preserve the ordering of the variable. – webelo Jul 01 '16 at 00:36
47

If you don't want this behaviour, don't use factors, use character vectors instead. I think this makes more sense than patching things up afterwards. Try the following before loading your data with read.table or read.csv:

options(stringsAsFactors = FALSE)

The disadvantage is that you're restricted to alphabetical ordering. (reorder is your friend for plots)

hadley
  • 94,313
  • 27
  • 170
  • 239
39

It is a known issue, and one possible remedy is provided by drop.levels() in the gdata package where your example becomes

> drop.levels(subdf)
  letters numbers
1       a       1
2       b       2
3       c       3
> levels(drop.levels(subdf)$letters)
[1] "a" "b" "c"

There is also the dropUnusedLevels function in the Hmisc package. However, it only works by altering the subset operator [ and is not applicable here.

As a corollary, a direct approach on a per-column basis is a simple as.factor(as.character(data)):

> levels(subdf$letters)
[1] "a" "b" "c" "d" "e"
> subdf$letters <- as.factor(as.character(subdf$letters))
> levels(subdf$letters)
[1] "a" "b" "c"
Dirk Eddelbuettel
  • 331,520
  • 51
  • 596
  • 675
  • 5
    The `reorder` parameter of the `drop.levels` function is worth mentioning: if you have to preserve the original order of your factors, use it with `FALSE` value. – daroczig Jan 17 '11 at 11:31
  • Using gdata for just drop.levels yields "gdata: read.xls support for 'XLS' (Excel 97-2004) files ENABLED." "gdata: Unable to load perl libaries needed by read.xls()" "gdata: to support 'XLSX' (Excel 2007+) files." "gdata: Run the function 'installXLSXsupport()'" "gdata: to automatically download and install the perl". Use droplevels from baseR (https://stackoverflow.com/a/17218028/9295807) – Vrokipal Jun 20 '18 at 19:12
  • Stuff happens over time. You _are_ commenting on an answer I wrote nine years ago. So let's take this as a hint to generally prefer base R solutions as those are the ones using functionality that is still going to be around _N_ years from now. – Dirk Eddelbuettel Jun 20 '18 at 19:21
26

Another way of doing the same but with dplyr

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

Edit:

Also Works ! Thanks to agenis

subdf <- df %>% filter(numbers <= 3) %>% droplevels
levels(subdf$letters)
Community
  • 1
  • 1
Prradep
  • 4,719
  • 3
  • 34
  • 66
17

For the sake of completeness, now there is also fct_drop in the forcats package http://forcats.tidyverse.org/reference/fct_drop.html.

It differs from droplevels in the way it deals with NA:

f <- factor(c("a", "b", NA), exclude = NULL)

droplevels(f)
# [1] a    b    <NA>
# Levels: a b <NA>

forcats::fct_drop(f)
# [1] a    b    <NA>
# Levels: a b
Aurèle
  • 10,219
  • 1
  • 26
  • 43
15

Here's another way, which I believe is equivalent to the factor(..) approach:

> df <- data.frame(let=letters[1:5], num=1:5)
> subdf <- df[df$num <= 3, ]

> subdf$let <- subdf$let[ , drop=TRUE]

> levels(subdf$let)
[1] "a" "b" "c"
ars
  • 106,073
  • 21
  • 135
  • 131
  • Ha, after all these years I didn't know there is a `\`[.factor\`` method that has a `drop` argument and you've posted this in 2009... – David Arenburg Feb 13 '19 at 15:42
8

This is obnoxious. This is how I usually do it, to avoid loading other packages:

levels(subdf$letters)<-c("a","b","c",NA,NA)

which gets you:

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

Note that the new levels will replace whatever occupies their index in the old levels(subdf$letters), so something like:

levels(subdf$letters)<-c(NA,"a","c",NA,"b")

won't work.

This is obviously not ideal when you have lots of levels, but for a few, it's quick and easy.

Matt Parker
  • 24,639
  • 6
  • 51
  • 71
8

Looking at the droplevels methods code in the R source you can see it wraps to factor function. That means you can basically recreate the column with factor function.
Below the data.table way to drop levels from all the factor columns.

library(data.table)
dt = data.table(letters=factor(letters[1:5]), numbers=seq(1:5))
levels(dt$letters)
#[1] "a" "b" "c" "d" "e"
subdt = dt[numbers <= 3]
levels(subdt$letters)
#[1] "a" "b" "c" "d" "e"

upd.cols = sapply(subdt, is.factor)
subdt[, names(subdt)[upd.cols] := lapply(.SD, factor), .SDcols = upd.cols]
levels(subdt$letters)
#[1] "a" "b" "c"
jangorecki
  • 14,077
  • 3
  • 57
  • 137
7

here is a way of doing that

varFactor <- factor(letters[1:15])
varFactor <- varFactor[1:5]
varFactor <- varFactor[drop=T]
David Arenburg
  • 87,271
  • 15
  • 123
  • 181
Diogo
  • 744
  • 2
  • 8
  • 14
6

I wrote utility functions to do this. Now that I know about gdata's drop.levels, it looks pretty similar. Here they are (from here):

present_levels <- function(x) intersect(levels(x), x)

trim_levels <- function(...) UseMethod("trim_levels")

trim_levels.factor <- function(x)  factor(x, levels=present_levels(x))

trim_levels.data.frame <- function(x) {
  for (n in names(x))
    if (is.factor(x[,n]))
      x[,n] = trim_levels(x[,n])
  x
}
Brendan OConnor
  • 9,048
  • 3
  • 25
  • 24
4

Very interesting thread, I especially liked idea to just factor subselection again. I had the similar problem before and I just converted to character and then back to factor.

   df <- data.frame(letters=letters[1:5],numbers=seq(1:5))
   levels(df$letters)
   ## [1] "a" "b" "c" "d" "e"
   subdf <- df[df$numbers <= 3]
   subdf$letters<-factor(as.character(subdf$letters))
DfAC
  • 355
  • 2
  • 6
  • I mean, `factor(as.chracter(...))` works, but just less efficiently and succinctly than `factor(...)`. Seems strictly worse than the other answers. – Gregor Thomas Feb 13 '19 at 15:47
1

Unfortunately factor() doesn't seem to work when using rxDataStep of RevoScaleR. I do it in two steps: 1) Convert to character and store in temporary external data frame (.xdf). 2) Convert back to factor and store in definitive external data frame. This eliminates any unused factor levels, without loading all the data into memory.

# Step 1) Converts to character, in temporary xdf file:
rxDataStep(inData = "input.xdf", outFile = "temp.xdf", transforms = list(VAR_X = as.character(VAR_X)), overwrite = T)
# Step 2) Converts back to factor:
rxDataStep(inData = "temp.xdf", outFile = "output.xdf", transforms = list(VAR_X = as.factor(VAR_X)), overwrite = T)
1

Have tried most of the examples here if not all but none seem to be working in my case. After struggling for quite some time I have tried using as.character() on the factor column to change it to a col with strings which seems to working just fine.

Not sure for performance issues.

Naga Pakalapati
  • 143
  • 2
  • 5
0

A genuine droplevels function that is much faster than droplevels and does not perform any kind of unnecessary matching or tabulation of values is collapse::fdroplevels. Example:

library(collapse)
library(microbenchmark)

# wlddev data supplied in collapse, iso3c is a factor
data <- fsubset(wlddev, iso3c %!in% "USA")

microbenchmark(fdroplevels(data), droplevels(data), unit = "relative")
## Unit: relative
##               expr  min       lq     mean   median       uq      max neval cld
##  fdroplevels(data)  1.0  1.00000  1.00000  1.00000  1.00000  1.00000   100  a 
##   droplevels(data) 30.2 29.15873 24.54175 24.86147 22.11553 14.23274   100   b
Sebastian
  • 459
  • 3
  • 8