-3

I have a data frame 'qlfs' which contains a column 'qlfs$TravelMode'.

The $TravelMode is a factor containing 10 levels:

levels(qlfs$TravelMode)
[1] "Non-working adult"                   
[2] "Car,van,minibus,works van"           
[3] "Motorbike,moped,scooter"             
[4] "Bicycle"                             
[5] "Bus,coach,private bus"               
[6] "Taxi"                                
[7] "Railway train"                       
[8] "Underground train,light railway,tram"
[9] "Walk"                                
[10] "Other method"                    

The dataset contains 90k + rows.

I would like to remove level 1 (Non-working adult) and any associated rows from the wider dataframe.

I have tried the following:

for (i in 1:NROW(qlfs$TravelMode)) {
   if(qlfs$TravelMode[i]="Non-working adult") {
       qlfs$TravelMode[i] <- "NA"
   }
}

Where I would then remove the NAs at a later point, but this did not work.

I have also looked at droplevels() function, but could not get this to work.

Can anybody point out where I am going wrong or suggest a better way to achieve this?

Cobain
  • 195
  • 1
  • 14
  • Try `qlfs_clean <- qlfs[ qlfs$TravelMode != "Non-working adult", ]` – zx8754 Oct 18 '16 at 10:47
  • 1
    Once you deleted the rows, like @zx8754 said, then droplevels – dww Oct 18 '16 at 10:48
  • I tried both and could not get this level to drop – Cobain Oct 18 '16 at 10:51
  • qlfs$TravelMode = factor (qlfs$TravelMode) – dww Oct 18 '16 at 10:52
  • I worked out the issue: the level I was trying to delete still contained entries. I removed the entries by removing the corresponding rows within the dataframe and then running factor(qlfs$TravelMode) which got rid of the now obsolete level. Cheers for your help guys – Cobain Oct 22 '16 at 12:37

1 Answers1

0

Just remove the rows you don't want and then recreate the factors.

d <- factor(letters[1:20])

d <- d[d != 'a']
d <- factor(d)

levels(d)
timcdlucas
  • 1,334
  • 8
  • 20
  • Whoops, sorry! I tried this and Non-working adults was still a level – Cobain Oct 18 '16 at 10:50
  • Then I think we'd need to see a reproducible example. – timcdlucas Oct 18 '16 at 10:59
  • I worked out what it was in the end, the factor() function would not work as the level still contained entries. I dropped all rows from the dataframe with the corresponding level and then when the entries were equal to 0 I ran factor() and it dropped the level. Cheers for your help – Cobain Oct 22 '16 at 12:38