【问题标题】:Aggregate function in R using two columns simultaneouslyR中的聚合函数同时使用两列
【发布时间】:2016-09-07 12:17:15
【问题描述】:

数据:-

df=data.frame(Name=c("John","John","Stacy","Stacy","Kat","Kat"),Year=c(2016,2015,2014,2016,2006,2006),Balance=c(100,150,65,75,150,10))

   Name Year Balance
1  John 2016     100
2  John 2015     150
3 Stacy 2014      65
4 Stacy 2016      75
5   Kat 2006     150
6   Kat 2006      10

代码:-

aggregate(cbind(Year,Balance)~Name,data=df,FUN=max )

输出:-

   Name Year Balance
1  John 2016     150
2   Kat 2006     150
3 Stacy 2016      75

我想使用 Year 和 Balance 两列来聚合/汇总上述数据框。我使用基本函数 aggregate 来执行此操作。我需要最近一年/最近一年的最大余额。输出的第一行,John 有最近的一年 (2016) 但余额是 (2015) ,这不是我需要的,它应该输出 100 而不是 150。我在哪里出错了?

【问题讨论】:

    标签: r aggregate summarization


    【解决方案1】:

    有点讽刺的是,aggregate 是一个糟糕的聚合工具。你可以让它工作,但我会这样做:

    library(data.table)
    
    setDT(df)[order(-Year, -Balance), .SD[1], by = Name]
    #    Name Year Balance
    #1:  John 2016     100
    #2: Stacy 2016      75
    #3:   Kat 2006     150
    

    【讨论】:

      【解决方案2】:

      我会建议使用库 dplyr:

      data.frame(Name=c("John","John","Stacy","Stacy","Kat","Kat"),
                 Year=c(2016,2015,2014,2016,2006,2006),
                 Balance=c(100,150,65,75,150,10)) %>% #create the dataframe
          tbl_df() %>% #convert it to dplyr format
          group_by(Name, Year) %>% #group it by Name and Year
          summarise(maxBalance=max(Balance)) %>% # calculate the maximum for each group
          group_by(Name) %>% # group the resulted dataframe by Name
          top_n(1,maxBalance) # return only the first record of each group
      

      【讨论】:

      • 不错,但我会使用@eddi 答案的副本:df %>% group_by(Name) %>% arrange(desc(Year),desc(Balance)) %>% filter(1)
      • @MaratTalipov 不错的答案!
      【解决方案3】:

      这是另一个没有 data.table 包的解决方案。

      先对数据框进行排序,

      df <- df[order(-df$Year, -df$Balance),]
      

      然后选择每个组中同名的第一个

      df[!duplicated[df$Name],]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2013-09-21
        • 2018-12-12
        相关资源
        最近更新 更多