R: Drop multiple levels in list from dataframe

Viewed 82

I'm looking to drop multiple levels of a variable based on values in a list. My actual variable has 300 levels, but the below code creates a smaller sample data frame with a similar structure.

species <- data.frame(c("onmy","lema","misa","icpu","onmy","lema","misa","icpu","pyov", "tacl"),c("1","2","4","5","3","1","8","10","0", "26"))
colnames(species) <- c("species","count" )

I can keep values in a data frame based on a list using the following code.

keep <- data.frame(species[ species$species %in% c("onmy","lema","misa","icpu"), ]) # Keeps desired species in list

For my current purpose listing levels to keep will not work because I would have to list ~ 100 levels. However, I can drop several levels by repeating the following line of code repeatedly only changing the level value.

keep2 <- droplevels(species[-which(species$species == "pyov"),])
keep2 <- droplevels(keep2[-which(keep2$species == "tacl"),])

However, this is not a very clean way of writing the code. Is there a way to drop levels of a variable based on a list that is similar to the way I keep value in the second code block? I've seen a lot of examples, but I haven't found anything that fits my case use

Edit: I want to feed it the list c("tacl", "pyov") and have it drop the levels I listed.

1 Answers

Use %in% instead of ==

droplevels( subset(species, species %in% levels(keep$species)))

Or if we want to enter a vector of values

droplevels(subset(species, !species %in% c("tacl", "pyov")))
Related