How to remove unused levels after filtering by factor?

Here's an example that was taken from a partner SO site .

# define a %not% to be the opposite of %in%
library(dplyr)
# data
f <- c("a","a","a","b","b","c")
s <- c("fall","spring","other", "fall", "other", "other")
v <- c(3,5,1,4,5,2)
(dat0 <- data.frame(f, s, v))
#  f      s v
#1 a   fall 3
#2 a spring 5
#3 a  other 1
#4 b   fall 4
#5 b  other 5
#6 c  other 2
(sp.tmp <- filter(dat0, s == "spring"))
#  f      s v
#1 a spring 5
(str(sp.tmp))
#'data.frame':  1 obs. of  3 variables:
# $ f: Factor w/ 3 levels "a","b","c": 1
# $ s: Factor w/ 3 levels "fall","other",..: 3
# $ v: num 5

      

df obtained from filter()

retained all levels from the original df.

What would be the recommended way to drop the unused level (s) i.e. "fall"

and "others"

, within dplyr

?

+3


source to share


2 answers


You can do something like:

dat1 <- dat0 %>%
  filter(s == "spring") %>% 
  droplevels()

      



Then

str(df)
#'data.frame':  1 obs. of  3 variables:
# $ f: Factor w/ 1 level "a": 1
# $ s: Factor w/ 1 level "spring": 1
# $ v: num 5

      

+20


source


you can use droplevels



 sp.tmp <- droplevels(sp.tmp)
 str(sp.tmp)
 #'data.frame': 1 obs. of  3 variables:
 #$ f: Factor w/ 1 level "a": 1
 #$ s: Factor w/ 1 level "spring": 1
# $ v: num 5

      

+2


source







All Articles