# [R] drop levels problem

Felipe Carrillo mazatlanmexico at yahoo.com
Mon Nov 29 20:01:33 CET 2010

```Hi all:
I am having trouble dropping levels, got a few hints online without success.
I was under the inpression that subset(......drop=TRUE) would work but it
doesn't

library(ggplot2)
library(hmisc)

x <- structure(list(first = c(38.2086, 43.1768, 43.146, 41.8044, 42.4232,
46.3646, 38.0813, 40.0745, 40.4889, 38.6246, 40.2826, 41.6056,
34.5353, 40.0768), second = c(43.3295, 42.4326, 38.8994, 37.0894,
42.3218, 46.1726, 39.1206, 41.2072, 42.4874, 40.2657, 38.7766,
40.8822, 42.0165, 49.2055), third = c(42.24, 42.992, 37.7419,
42.3448, 41.9131, 44.385, 42.7811, 44.1963, 40.8088, 43.9634,
38.7079, 38.0791, 44.3136, 39.5333)), .Names = c("first", "second",
"third"), class = "data.frame", row.names = c(NA, -14L))

xmelt <- melt(x)
names(xmelt) <- c("year","fatPerc")

# Year variable is a factor with three levels
# Subset to plot only 'first' year
firstyear <- subset(xmelt,year=='first');str(firstyear)
# Plot showing three levels still after I made the subset
ggplot(firstyear,aes(year,fatPerc)) + geom_boxplot() + geom_jitter()

# Try to drop the levels but dropUnusedLevels() doesn't seem to work here
dropUnusedLevels()
ggplot(firstyear,aes(year,fatPerc)) + geom_boxplot() + geom_jitter()

# code below also should drop levels but it doesn't
#data.frame(lapply(firstyear, function(x) if (is.factor(x)){ factor(x)}
else{x}))
str(firstyear)

Felipe D. Carrillo
Supervisory Fishery Biologist
Department of the Interior
US Fish & Wildlife Service
California, USA

```