【问题标题】:Subset R dataframe based on proportion of total column value基于总列值比例的子集 R 数据框
【发布时间】:2018-05-14 19:27:56
【问题描述】:

我有一个数据框df,如下所示(示例以便于询问):

ID       Sales
10001   214108 
10002   207858
10003    76548
10004    68361
10005    56456

我需要对df 进行子集化,这样结果行将包含总销售额的 90%。我遇到了这个approach,但我没有得到想要的结果。我使用的是以下内容:

subset(df, Sales >= quantile(Sales,0.9))

我得到的是以下内容:

     >ID  Sales
     <dbl>  <dbl>
  1 10001 214108

我目前的想法是按照以下方式进行:

  1. 使用以下命令添加新列:df$Sales_pct = Sales/sum(Sales)
  2. Sales_pct 列值的降序对df 进行排序
  3. 添加另一个具有累积百分比的列,然后子集累积百分比值小于 0.9 的行

但是,我觉得应该有更好的方法来解决这个问题。有人可以帮忙吗?

【问题讨论】:

    标签: r dataframe subset


    【解决方案1】:

    使用 R 基础方法:

    #1.Add a new column using: df$Sales_pct = Sales/sum(Sales)
    df$Sales_pct <- with(df, Sales/sum(Sales))
    
    #2.Sort df in descending order of Sales_pct column values
    df <- df[order(df$Sales_pct, decreasing = TRUE), ]
    
    #3.Add another column with cumulative percentage and then subset rows that have 
    # the cumulative percentage value less than 0.9
    df$Sales_cum <- cumsum(df$Sales_pct)
    subset(df, Sales_cum < .90)
    
         ID  Sales Sales_pct Sales_cum
    1 10001 214108 0.3434901 0.3434901
    2 10002 207858 0.3334633 0.6769533
    3 10003  76548 0.1228047 0.7997581
    

    tidyverse 方法

    df %>% mutate(Sales_pct = Sales/sum(Sales)) %>% 
      arrange(-Sales_pct) %>% 
      mutate(Sales_cum = cumsum(Sales_pct)) %>% 
      filter(Sales_cum <= 0.90)
    

    【讨论】:

    • tidyverse 方法对我有用,所以我接受答案。
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2023-04-08
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多