Q:

Subset dataframe based on level of a factor

I have dataframe df1:
df1 <- data.frame(respondent = factor(c(1, 2, 3, 4, 5, 6, 7)),
                 location = factor(c("California", "Oregon", "Oregon",
                                     "Texas", "Oregon", "Mexico", "Canada")))

I want to subset it so that only rows with level Oregon of factor location remain in the dataframe:
df2 <- data.frame(respondent = factor(c(2, 3, 5)),
                 location = factor(c("Oregon", "Oregon",
                                     "Oregon")))

What's the most straightforward way to subset a dataframe based on a level of a dataframe?

A:

We can use subset and wrap with droplevels to drop the unused levels as it is a factor column
df2 <- droplevels(subset(df1, location == 'Oregon'))

