【问题标题】:How to group factors with low frequence into an 'other' factor in R如何将低频因子分组为R中的另一个因子
【发布时间】:2016-04-06 12:46:16
【问题描述】:
# Generate counts table
library(plyr)
example <- data.frame(count(diamonds,c('color', 'cut')))
example[1:3,]

# Excerpt of table
       color  cut   freq
1      D      Fair  163
2      D      Good  662
3      D Very Good 1513

您可以使用example[example$freq &gt; 1000,] 轻松过滤频率 > 1000 的表。我想生成一个与此类似的表,除非所有值都小于一个值,例如1000 包含在一行中 (Other) 类似于当您有太多因素并调用 summary(example, maxsum=3) 时发生的情况。

     color         cut          freq     
 D      : 5   Fair   : 7   Min.   : 119  
 E      : 5   Good   : 7   1st Qu.: 592  
 (Other):25   (Other):21   Median :1204  
                           Mean   :1541  
                           3rd Qu.:2334  
                           Max.   :4884 

理想输出示例:

理想情况下我想转换这个example[example$color=='J',]:

 color   cut freq
 J      Fair  119
 J      Good  307
 J Very Good  678
 J   Premium  808
 J     Ideal  896

并产生这个:

 color       cut freq
     J Very Good  678
     J   Premium  808
     J     Ideal  896
     J   (Other)  426 

奖励: 如果可以使用 ggplot 进行这种过滤来创建如下图,但是使用这种过滤,那也很棒。

ggplot(example, aes(x=color, y=freq)) + geom_bar(aes(fill=cut), stat = "identity")

【问题讨论】:

  • 那么Other 的门槛是多少?
  • @mtoto 我不介意这个数字,但我希望将小于阈值的“剪切”因子的频率分组(按颜色)。可能是频率
  • @docendodiscimus,谢谢你的链接,我去看看。
  • @amblina 是你要找的吗?

标签: r ggplot2 dataframe dplyr summary


【解决方案1】:

这是使用dplyr 将正确数据直接通过管道传递到ggplot 调用的替代方法。

library(dplyr)
example %>% mutate(cut = ifelse(freq < 500, "Other", levels(cut))) %>%
  group_by(color, cut) %>%
  summarise(freq = sum(freq)) %>%
  ggplot(aes(color, freq, fill = cut)) +
  geom_bar(stat = "identity")

一定要分离plyr,否则dplyr调用的输出会不正确。

【讨论】:

    【解决方案2】:

    试试这个:

    library(plyr)
    library(ggplot2)
    example <- data.frame(count(diamonds,c('color', 'cut')))
    
    
    # Compute the row id where frequency is lower than some threshold
    idx <- example$freq < 1000
    
    # Create a helper function that adds the level "Other" to a vector
    add_other_level <- function(x){
      levels(x) <- c(levels(x), "Other")
      x
    }
    
    # Change the factor leves for the threshold id rows
    example <- within(example, 
           {
             color <- add_other_level(color)
             color[idx] <- "Other"
             cut <- add_other_level(cut)
             cut[idx]    <- "Other"
           }
    )
    
    # Create a plot
    ggplot(example, aes(x = color, y = freq, fill = cut)) + 
      geom_bar(stat = "identity")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多