【问题标题】:Finding max value for a column in dataframe for each day in R [duplicate]在R中查找数据框中每一列的最大值[重复]
【发布时间】:2014-08-06 14:32:32
【问题描述】:

需要在数据框中找到列数的最大值并按天分组。这是它拥有的样本数据:

Date               count
7/28/2014 00:30:31  95
7/28/2014 01:30:57  62
7/28/2014 15:42:42  112
7/28/2014 15:42:42  150
7/31/2014 17:12:22  12
7/31/2014 04:45:47  97
8/2/2014  21:12:06  85
8/2/2014 23:05:09   96
8/2/2014 18:17:42   48
8/2/2014 19:53:02   89
8/2/2014 14:18:38   201

我的要求是找到计数的最大值。这怎么能在 R 中完成?

对不起,我忘了提。日期列的数据类型为时间戳或具有时间戳格式值。

【问题讨论】:

    标签: r


    【解决方案1】:

    假设您的数据在一个名为bardata.frame 中,您可以使用by()

    > with(bar,by(count,Date,max))
    Date: 7/28/2014
    [1] 150
    -------------------------
    Date: 7/31/2014
    [1] 97
    -------------------------
    Date: 8/2/2014
    [1] 201
    

    【讨论】:

    • 这适用于日期数据类型,但不适用于时间戳。你能提供时间戳的答案吗
    【解决方案2】:

    有很多方法可以做到这一点,使用 base R 的另一个选项是使用aggregate(假设您的数据称为dat):

    aggregate(count ~ Date, data = dat, max)
    #       Date count
    #1 7/28/2014   150 
    #2 7/31/2014    97
    #3  8/2/2014   201
    

    使用包dplyr,以防您有大量数据集并需要更快的速度:

    library(dplyr)
    
    dat %>% group_by(Date) %>% summarize(maxCount = max(count))
    #Source: local data frame [3 x 2]
    #
    #       Date maxCount
    #1 7/28/2014      150
    #2 7/31/2014       97
    #3  8/2/2014      201
    

    【讨论】:

      【解决方案3】:

      data.table 用于更大的数据集

       library(data.table)
       setDT(dat)[, list(maxCount=max(count)), by=Date]
       #        Date maxCount
       #1: 7/28/2014   150
       #2: 7/31/2014    97
       #3:  8/2/2014   201
      

      稍大数据集的基准

      set.seed(455)
      dat1 <- data.frame(group=sample(1:5000, 1e7, replace=TRUE), count=sample(200, 1e7, replace=TRUE))
      
      f1<- function() dat1 %>% group_by(group) %>% summarize(maxCount = max(count))
      
      f2 <- function() setDT(dat1)[, list(maxCount=max(count)), by=group]
      library(microbenchmark)
      microbenchmark(f1(),f2(), unit="relative")
      # expr      min       lq   median       uq      max neval
      # f1() 1.914458 2.049166 2.221317 2.256047 2.888778   100
      # f2() 1.000000 1.000000 1.000000 1.000000 1.000000   100
      

      【讨论】:

        【解决方案4】:

        tapply 语法简单,并提供清晰的表格输出:

        with(ddf, tapply(count, Date, max))
        7/28/2014 7/31/2014  8/2/2014 
              150        97       201 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 2015-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多