使用dplyr过滤数据帧后,从一个因素中删除未使用的级别

use*_*705 5 r plyr dplyr

我使用dplyr函数创建了一个新数据集,其中包含少于4行的名称。

df <- data.frame(name = c("a", "a", "a", "b", "b", "c", "c", "c", "c"), x = 1:9)

aa = df %>%
    group_by(name) %>%
    filter(n() < 4)
Run Code Online (Sandbox Code Playgroud)

但是当我打字

table(aa$name)
Run Code Online (Sandbox Code Playgroud)

我明白了

a b c 
3 2 0 
Run Code Online (Sandbox Code Playgroud)

我想让我的输出如下

a b 
3 2 
Run Code Online (Sandbox Code Playgroud)

如何将新框架aa与df完全分开?

mpa*_*nco 7

要完成您的答案和KoenV的评论,您只需在一行中编写解决方案或应用该功能即可factor删除未使用的级别:

table(droplevels(aa$name))
table(factor(aa$name))
Run Code Online (Sandbox Code Playgroud)

或因为您在末尾使用dplyr添加droplevels

aa <- df %>%
       group_by(name) %>%
       filter(n() < 4) %>% 
       droplevels()
table(aa$name)

# Without using table
df %>%
  group_by(name) %>%
  summarise(count = n()) %>% 
  filter(count < 4)
Run Code Online (Sandbox Code Playgroud)


use*_*705 0

 aaNew <- droplevels(aa)
 table(aa$name)
Run Code Online (Sandbox Code Playgroud)

  • 请在您的答案中添加一个小解释 (4认同)