Reputation: 449
I have a large data frame that I'm trying to subset and then table. In order to get rid of unused levels inherited from the superset (the original data frame), I use droplevels()
, but this somehow messes up the counts in table()
:
#without droplevels()
unknownMun <- table(unknown$MUNICIPALITY_NAME)
unknownMun <- unknownMun[unknownMun >= 1]
> unknownMun
Albertslund Kommune Allerød Kommune Ballerup Kommune Bornholm Kommune Brøndby Kommune Dragør Kommune Egedal Kommune
14 32 88 9 30 3 18
Frederiksberg Kommune Frederikssund Kommune Furesø Kommune Gentofte Kommune Gladsaxe Kommune Glostrup Kommune Gribskov Kommune
53 38 10 43 21 41 53
Halsnæs Kommune Helsingør Kommune Herlev Kommune Hillerød Kommune Hvidovre Kommune Høje-Taastrup Kommune Hørsholm Kommune
80 23 46 35 22 2 70
Københavns Kommune Lyngby-Taarbæk Kommune Rudersdal Kommune
560 93 34
If I do the same with droplevels()
, this is what I get:
levels(unknown$MUNICIPALITY_NAME) <- droplevels(unknown$MUNICIPALITY_NAME)
unknownMun <- table(unknown$MUNICIPALITY_NAME)
> unknownMun
Københavns Kommune Frederiksberg Kommune Glostrup Kommune Brøndby Kommune Rødovre Kommune Albertslund Kommune Høje-Taastrup Kommune
1440 0 0 0 0 0 0
Hvidovre Kommune Herlev Kommune Ballerup Kommune Tårnby Kommune Dragør Kommune Lyngby-Taarbæk Kommune Gentofte Kommune
0 0 0 0 0 0 0
Rudersdal Kommune Gladsaxe Kommune Hørsholm Kommune Helsingør Kommune Gribskov Kommune Halsnæs Kommune Hillerød Kommune
0 0 0 0 0 0 0
Allerød Kommune Furesø Kommune Frederikssund Kommune Egedal Kommune Bornholm Kommune
0 0 0 0 0
Can anybody explain what goes wrong here and how to fix it?
I really prefer something like droplevels()
because the tables get differing lengths when I use the x[x >= 1]
operator and I'm trying to compare them.
Upvotes: 1
Views: 141
Reputation: 20399
droplevels
works on data.frames
and factors
respectively not on the levels of the factor
.
So you should either do:
unknown$MUNICIPALITY_NAME <- droplevels(unknown$MUNICIPALITY_NAME)
or
unknown <- droplevels(unknown)
Upvotes: 1
Reputation: 57696
That should be
unknown$MUNICIPALITY_NAME <- droplevels(unknown$MUNICIPALITY_NAME)
without the call to levels
on the left-hand side.
Upvotes: 2