【问题标题】:Group_by multiple columns and summarise unique columnGroup_by 多列并汇总唯一列
【发布时间】:2021-11-14 02:10:20
【问题描述】:

我在下面有一个数据集

family type inc name
AA success 30000 Bill
AA ERROR 15000 Bess
CC Pending 22000 Art
CC Pending 18000 Amy
AA Serve not respnding d 25000 Paul
ZZ Success 50000 Pat
ZZ Processing 50000 Pat

我想按多列分组

下面是我的代码

df<-df1%>%
group_by(Family , type)%>%
  summarise(Transaction_count = n(), Face_value = sum(Inc))%>%
  mutate(Pct = Transaction_count/sum(Transaction_count))

我想要的是任何有相同观察的家庭,它应该只选择一个

如下图所示。

谢谢

【问题讨论】:

    标签: r dplyr r-markdown tidyverse


    【解决方案1】:

    您可以使用duplicated 将重复值替换为空白值。

    library(dplyr)
    
    df %>%
      group_by(family , type)%>%
      summarise(Transaction_count = n(), Face_value = sum(inc))%>%
      mutate(Pct = Transaction_count/sum(Transaction_count), 
             family = replace(family, duplicated(family), '')) %>%
      ungroup
    
    #   family type                     Transaction_count Face_value   Pct
    #  <chr>  <chr>                                <int>      <int> <dbl>
    #1 "AA"   ERROR                                    1      15000 0.333
    #2 ""     Serve not respnding    d                 1      25000 0.333
    #3 ""     success                                  1      30000 0.333
    #4 "CC"   Pending                                  2      40000 1    
    #5 "ZZ"   Processing                               1      50000 0.5  
    #6 ""     Success                                  1      50000 0.5  
    

    如果您需要用于显示目的的数据,您可以查看 formattablekable 等软件包。

    数据

    如果您在reproducible format 中提供数据会更容易提供帮助

    df <- structure(list(family = c("AA", "AA", "CC", "CC", "AA", "ZZ", 
    "ZZ"), type = c("success", "ERROR", "Pending", "Pending", "Serve not respnding    d", 
    "Success", "Processing"), inc = c(30000L, 15000L, 22000L, 18000L, 
    25000L, 50000L, 50000L), name = c("Bill", "Bess", "Art", "Amy", 
    "Paul", "Pat", "Pat")), row.names = c(NA, -7L), class = "data.frame")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2021-04-29
      相关资源
      最近更新 更多