【问题标题】:Collapse Dataframe values under one New group在一个新组下折叠数据框值
【发布时间】:2020-03-17 21:13:48
【问题描述】:

我已经为这个问题的答案做了一些搜索,但是我不完全确定如何提出这个问题,所以在大多数情况下,搜索都是徒劳的。

假设我有一个看起来像这样的 DF

customer, revenue
a, 2000 
b, 2000 
c, 3000 
Microsoft, 4000 
Oracle, 5000 

我想要一个包含三个堆栈的堆积条形图......其他,Oracle 和 Microsoft。其他将是折叠所有不是微软或甲骨文的东西并将收入相加的结果。微软和甲骨文将自立门户。

条形图将是一个条形图,总值为 16,000,单个堆栈为 (Other=7000, Microsoft = 4000, Oracle=5000)

希望这是有道理的。

我现在的代码会分别列出所有客户。实际上,这里有更多的客户,因此条形图将无法阅读。

finalData <- finalData %>% 
group_by(product, customer) %>%
summarize(revenue = sum(revenue))

是否有一些我可以执行的变异或附加 group_by 操作将折叠所有不在standAloneCustomers 中的所有内容并将其命名为“其他”?

感谢您的帮助。

【问题讨论】:

  • 在您的问题中,“产品”列未显示在数据中

标签: r dplyr


【解决方案1】:

我们可以将“Microsoft”、“Oracle”以外的值replace转为“Other”和summarise,得到“revenue”的sum

library(dplyr)
library(ggplot2)
finalData %>% 
      group_by(product, customer = replace(customer, 
         !customer %in% c("Microsoft", "Oracle"), "Other")) %>%
       summarise(revenue = sum(revenue)) %>%
    ggplot(aes(x= product, y=revenue, fill = customer)) +
       geom_col()

数据

finalData <- structure(list(customer = c("a", "b", "c", "Microsoft", "Oracle"
), revenue = c(2000, 2000, 3000, 4000, 5000), product = c("A", 
"A", "A", "A", "A")), row.names = c(NA, -5L), class = "data.frame")

【讨论】:

    【解决方案2】:
    library(ggplot2)
    library(dplyr)
    dat <- read.csv(header=TRUE, stringsAsFactors=FALSE, text="
    customer, revenue
    a, 2000 
    b, 2000 
    c, 3000 
    Microsoft, 4000 
    Oracle, 5000 ")
    
    
    dat %>%
      mutate(customer = if_else(customer %in% c("Microsoft", "Oracle"), customer, "Other")) %>%
      group_by(customer) %>%
      summarize(revenue = sum(revenue)) %>%
      ggplot(aes(x='', y=revenue)) +
      geom_bar(aes(fill = customer), stat = "identity") +
      xlab(NULL)
    

    【讨论】:

      【解决方案3】:

      这是aggregate 的基本 R 解决方案

      dfout <- aggregate(.~customer,
                         within(df,customer <- ifelse(customer%in%c("Microsoft","Oracle"),customer,"other")),
                         sum)
      

      这样

      > dfout
         customer revenue
      1 Microsoft    4000
      2    Oracle    5000
      3     other    7000
      

      数据

      df <- structure(list(customer = c("a", "b", "c", "Microsoft", "Oracle"
      ), revenue = c(2000L, 2000L, 3000L, 4000L, 5000L)), class = "data.frame", row.names = c(NA, 
      -5L))
      

      【讨论】:

        猜你喜欢
        • 2014-10-22
        • 2021-07-12
        • 1970-01-01
        • 2021-04-11
        • 2013-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        相关资源
        最近更新 更多