繁体   English   中英

如何用前n个级别替换因子级别(按发生次数)

[英]How can I replace a factor levels with the top n levels (by number of occurances)

这个问题与我如何用前n个水平(按某种度量标准)加上[other]替换因子水平有关? 作为指标,我想使用该因素的出现次数。 我知道我可以通过列出发生的事情来做到这一点,但我想知道是否有更漂亮的方法。

例:

library(data.table);
library(plyr);
fac <- data.table(score = as.factor(c(3,4,5,3,3,3,5)));
ocCnt <- data.table(lapply(fac,count)$score);
fac$occurrence <- 0;
for(i in 1:length(fac$score)){fac$occurrence[i]<-ocCnt[x==fac$score[i]]$freq};

然后,我可以使用参考的问题/答案中描述的功能:

hotfactor= function(fac,by,n=10,o="other") {
   levels(fac)[rank(-xtabs(by~fac))[levels(fac)]>n] <- o
   fac
}

继续这个例子,如果我们只想看看最受欢迎的因素,我们这样做:

hotfactor(fac$score,fac$occurrence,1);

获得答案:

[1] 3其他3 3 3其他

等级:3其他

所以我的问题是,我可以不必添加一个统计发生次数的列表来执行此操作吗?

请注意,我要针对n个最受欢迎的因素(而不只是针对最受欢迎的因素)执行此操作。

使用tablewhich.max

score <- factor(c(3,4,5,3,3,3,5))
levels(score)[- which.max(table(score))] <- "other"
#[1] 3     other other 3     3     3     other
#Levels: 3 other

显然,这通过取第一个最大值来打破联系。

如果要保留前两个级别:

score <- factor(c(3, 4,5,3,3,3,5), levels =c(4,3,5))

levels(score)[!levels(score) %in% names(sort(table(score), decreasing = TRUE)[1:2])] <- "other"
#[1] 3     other 5     3     3     3     5    
#Levels: other 3 5

如果您不知道需要分组多少个级别(即90%的数据)并且愿意使用dplyr ,则可以按照以下步骤进行操作:

library(dplyr)

df <- data.frame(
        f = factor(mapply(rep, letters[1:5], 2^(1:5)) %>% unlist(use.names = F))
)

df %>% 
    count(f, sort = T) %>% 
    mutate(p = cumsum(n) / nrow(df))

#      A tibble: 5 x 3
#        f     n         p
#   <fctr> <int>     <dbl>
# 1      e    32 0.5161290
# 2      d    16 0.7741935
# 3      c     8 0.9032258
# 4      b     4 0.9677419
# 5      a     2 1.0000000

(top <- df %>% 
    count(f, sort = T) %>% 
    mutate(p = cumsum(n) / nrow(df)) %>%
    filter(cumall(p < .91)) %>% 
    select(f) %>% 
    unlist(use.names = F))

# [1] e d c
# Levels: a b c d e

levels(df$f) <- factor(c(levels(df$f), 'z'))
df$f[!df$f %in% top] <- 'z'

df %>% 
    count(f, sort = T) %>% 
    mutate(p = cumsum(n) / nrow(df))

#  A tibble: 4 x 3
#        f     n         p
#   <fctr> <int>     <dbl>
# 1      e    32 0.5161290
# 2      d    16 0.7741935
# 3      c     8 0.9032258
# 4      z     6 1.0000000

暂无
暂无

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

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