You can use the drop argument with the subset operator ( [] )
> g5 <- factor(LETTERS[1:5])
> g5
[1] A B C D E
> g4 <- g5[1:4]
> g4 # note levels are printed since they do not match the values
[1] A B C D
Levels:
[1] "A" "B" "C" "D" "E"
> g4drop <- g4[drop=TRUE]
> g4drop # levels are not printed since there is no mismatch
[1] A B C D
Here is another example using a sample subset from fuel.frame:
> smallish.cars <- fuel.frame[fuel.frame$Type %in% c("Compact", "Small",
"Sporty"),]
> smallish.cars
Weight Disp. Mileage Fuel Type
Eagle Summit 4 2560 97 38 3.030303 Small
Ford Escort 4 2345 114 38 3.030303 Small
Ford Festiva 4 1845 81 42 2.702703 Small
Honda Civic 4 2260 91 37 3.125000 Small
Mazda Protege 4 2440 113 37 3.125000 Small
Mercury Tracer 4 2285 97 31 3.846154 Small
... <snip>
# -- Display current levels of factor
levels(smallish.cars$Type)
> levels(smallish.cars$Type)
[1] "Compact" "Large" "Medium" "Small" "Sporty" "Van"
# Use drop parameter
# of subset operator to
# remove unused levels
> smallish.cars$Type <- smallish.cars$Type[drop=T]
# -- Display current levels of factor
> levels(smallish.cars$Type)
[1] "Compact" "Small" "Sporty"