在 R 中使用 dplyr 进行过滤时,为什么过滤掉的变量级别仍保留在过滤后的数据中?

When filtering with dplyr in R, why do filtered out levels of a variable remain in filtered data?

我正在尝试使用 dplyr 包中的 filter 命令过滤掉一堆数据。一切似乎都按照我希望的那样进行,但是当我尝试从新过滤的数据中绘制一些图表时,我过滤掉的所有级别都显示出来了(尽管没有值)。但是他们在那里的事实仍然使我的水平轴偏离。

所以两个问题:

1) 为什么这些过滤后的级别仍在数据中?

2) 如何过滤以使这些不再存在?

这是一个小例子,你可以运行明白我在说什么:

library(dplyr)
library(ggvis)

# small example frame
data <- data.frame(
  x = c(1:10),
  y = rep(c("yes", "no"), 5)
)

# filtering to only include data with "yes" in y variable
new_data <- data %>%
  filter(y == "yes")

levels(new_data) ## Why is "no" showing up as a level for this if I've filtered that out?

# Illustration of the filtered values still showing up on axis
new_data %>%
  ggvis(~y, ~x) %>%
  layer_bars()

感谢您的帮助。

R 中的因子在过滤时不会自动降低水平。您可能认为这是一个愚蠢的默认设置(我认为),但它很容易处理——只需对结果使用 droplevels 函数即可。

new_data <- data %>%
  filter(y == "yes") %>%
  droplevels
levels(new_data$y)
## [1] "yes"

如果你一直这样做,你可以定义一个新函数

dfilter <- function(...) droplevels(filter(...))