-2

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?

KaC
  • 267
  • 1
  • 5
  • 15

1 Answers1

0

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'))
akrun
  • 674,427
  • 24
  • 381
  • 486