arpit joshi
arpit joshi

Reputation: 2134

Subset data frame based on variable whose type is factor

I have a data frame carList . It has a variable State which is of type factor ,example :

Price Year Mileage City  State  Make  Model  
8600 2016   14872  Miami  FL    Honda Civic

I want to subset carList whose state is "CA"

> nlevels(carList$State)
[1] 59 

subsetForCA <- subset(carList,carList$State=="CA")

But I get No results .How can I subset the above data set based on State which is a factor ?

Upvotes: 1

Views: 35

Answers (1)

akrun
akrun

Reputation: 887158

The issue could be due to leading/lagging spaces. If that is the case, trimws could remove if there any of those spaces, and then do a == on that trimmed column

subset(carList, trimws(State) == "CA")

This can also be done with tidyverse

library(tidyverse)
carList %>%
     filter(str_trim(State) == "CA")

Upvotes: 2

Related Questions