这是一个取自 a fellow SO member 的示例.
# 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
由filter()
产生的df保留了原始 df 的所有级别。
删除未使用级别的推荐方法是什么,即 "fall"
和"others"
,在dplyr
内框架?
最佳答案
你可以这样做:
dat1 <- dat0 %>%
filter(s == "spring") %>%
droplevels()
然后
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
关于r - 按因子过滤后如何删除未使用的级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826865/