filter - Filtering a data frame in R and an unwanted filtered out result -


this snippet:

names<-c("alice","bob","charlie") ages<-c(25,24,25) friends<-data.frame(names,ages) a25 <- friends[friends$age==25,] a25 table(a25$names) 

gives me output

    names ages 1   alice   25 3 charlie   25    alice     bob charlie        1       0       1 

now, why "bob" in output since data frame a25 not include "bob"? expected output (from table command):

  alice  charlie        1        1  

what missing?

my environment:

r version 2.15.2 (2012-10-26) platform: i386-w64-mingw32/i386 (32-bit) 

this question appears have answer in comments. answer shares 1 additional approach , consolidates suggestions comments.

the problem describe follows: there no "bob" in "a25$names" variable, when use table, "bob" shows up. because levels present in original column have been retained.

table(a25$names) #  #   alice     bob charlie  #       1       0       1  

fortunately, there's function called droplevels takes care of situations this:

table(droplevels(a25$names)) #  #   alice charlie  #       1       1  

the droplevels function can work on data.frame too, allowing following:

a25alt <- droplevels(friends[friends$ages==25,]) a25alt #     names ages # 1   alice   25 # 3 charlie   25 table(a25alt$names) #  #   alice charlie  #       1       1  

as mentioned in comments, @ as.character , factor:

table(as.character(a25$names)) table(factor(a25$names)) 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -