factor variable filtered

When filter() is applied to a factor variable, it does the intended job. But, when I use table() afterwards on the new data frame, the dropped variable still appears with 0. I know if I convert the variable to character and then make it factor again, this problem will go away. Are there any better solution than this?

library(dplyr)
df_old <- tibble(var = factor(c("A", "B", "C", "B", "A", "k")))
# Drop k
df_new <- filter(df_old, var != "k")
table(df_new$var) # how do i get rid of k from table?      
#> 
#> A B C k 
#> 2 2 1 0

tidyverse include the forcats package which has useful factor handling functions. In this case fct_drop() comes to mind.

library(dplyr)
library(forcats)
df_old <- tibble(var = factor(c("A", "B", "C", "B", "A", "k")))
# Drop k
df_new <- filter(df_old, var != "k")
table(fct_drop(df_new$var))
1 Like