This function removes unused levels of a factor or in a data.frame. See examples.
rm.unused.levels(x, v = NULL)
a factor or a data frame
a list of variables (optional, if x
is a data frame)
If x
is a data frame, only factor variables of x
will be impacted.
If a list of variables is provided through v
, only the unused levels of the
specified variables will be removed.
df <- data.frame(v1 = c("a", "b", "a", "b"), v2 = c("x", "x", "y", "y"))
df$v1 <- factor(df$v1, c("a", "b", "c"))
df$v2 <- factor(df$v2, c("x", "y", "z"))
df
#> v1 v2
#> 1 a x
#> 2 b x
#> 3 a y
#> 4 b y
str(df)
#> 'data.frame': 4 obs. of 2 variables:
#> $ v1: Factor w/ 3 levels "a","b","c": 1 2 1 2
#> $ v2: Factor w/ 3 levels "x","y","z": 1 1 2 2
str(rm.unused.levels(df))
#> 'data.frame': 4 obs. of 2 variables:
#> $ v1: Factor w/ 2 levels "a","b": 1 2 1 2
#> $ v2: Factor w/ 2 levels "x","y": 1 1 2 2
str(rm.unused.levels(df, "v1"))
#> 'data.frame': 4 obs. of 2 variables:
#> $ v1: Factor w/ 2 levels "a","b": 1 2 1 2
#> $ v2: Factor w/ 3 levels "x","y","z": 1 1 2 2