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.droplevels()
function.read.table
or read.csv
: drop.levels()
in the gdata package where your example becomesdropUnusedLevels
function in the Hmisc package. However, it only works by altering the subset operator [
and is not applicable here.as.factor(as.character(data))
:dplyr
fct_drop
in the forcats
package http://forcats.tidyverse.org/reference/fct_drop.html.droplevels
in the way it deals with NA
:factor(..)
approach: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.setdiff
to find the subset of objects in the global environment (as returned by ls()
) that don't have mode function
(as returned by lsf.str()
)setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).