【问题标题】:R: drop factors with certain valuesR:具有特定值的下降因子
【发布时间】:2022-07-23 04:25:54
【问题描述】:

我有一个 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

有什么指导吗?

【问题讨论】:

  • 使用 c("C", "D", "G") 而不是 C,因为 C 是一个对象,而 "C" 是一个字符串/向量
  • 我认为您不想删除因素...我认为您想删除级别和这些级别的相应行,对吗?
  • @socialscientist 是的,这是正确的

标签: r dataframe r-factor drop


【解决方案1】:

您可以使用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"

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 1970-01-01
    • 2018-12-13
    • 2021-04-17
    • 2020-10-09
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多