繁体   English   中英

R:具有特定值的下降因子

[英]R: drop factors with certain values

我有一个包含因子列的data.frame 我想(a)从data.frame中删除该列中的值未出现在至少 8 行中的任何行,并(b)从因子中删除这些级别。

在以下情况下,它将是因子 C、D 和 G。

> table(x.train$oilType)

 A  B  C  D  E  F  G 
30 21  3  6  9  8  2 

据我所知,“droplevels”仅在根本不使用该因子时才有效。 我试了一下,没有成功。

> droplevels(x.train$oilType[-c(C,D,G)])
Error in NextMethod("[") : object 'G' not found

有什么指导吗?

您可以使用add_count()获取因子的每个值的计数,然后使用filter()保留计数>= 8的行。 然后,您可以使用droplevelsmutate来降低关卡。

library(dplyr)

# Example factor
df <- data.frame(fac = as.factor(c(rep("a", 3), rep("b", 8), rep("c", 9))))
df$fac %>% table()
#> .
#> a b c 
#> 3 8 9

# Keep only rows where the value of `fac` for that row is observed in at least
# 8 rows and drop unused levels
result <- df %>%
  add_count(fac) %>%
  filter(n >= 8) %>%
  mutate(fac = droplevels(fac))

print(result)
#>    fac n
#> 1    b 8
#> 2    b 8
#> 3    b 8
#> 4    b 8
#> 5    b 8
#> 6    b 8
#> 7    b 8
#> 8    b 8
#> 9    c 9
#> 10   c 9
#> 11   c 9
#> 12   c 9
#> 13   c 9
#> 14   c 9
#> 15   c 9
#> 16   c 9
#> 17   c 9

levels(result$fac)
#> [1] "b" "c"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM