【问题标题】:Aggregate data by week, month etc in R在 R 中按周、月等聚合数据
【发布时间】:2013-10-31 20:40:34
【问题描述】:

我需要汇总我的数据Kg

            Data  Kg
    1 2013-03-01 271
    2 2013-03-06 374
    3 2013-03-07  51
    4 2013-03-12 210
    5 2013-03-13 698
    6 2013-03-15 328

按周或月。我找到了这个答案here in stackoverflow,但我真的不明白答案。谁能告诉我我该怎么做这个案子。谢谢

【问题讨论】:

    标签: r


    【解决方案1】:

    提到的答案建议您应该使用xts 包。

    library(xts)
    ## create you zoo objects using your data
    ## you replace text argument by read.zoo(yourfile, header = TRUE)
    x.zoo <- read.zoo(text='  Data  Kg         
    +     1 2013-03-01 271
    +     2 2013-03-06 374
    +     3 2013-03-07  51
    +     4 2013-03-12 210
    +     5 2013-03-13 698
    +     6 2013-03-15 328',header=TRUE)
    ### then aggregate
    apply.weekly(x.zoo, mean)   ## per week
    apply.monthly(x.zoo, mean)   ## per month
    

    ??apply.xxxly:

    本质上是 xts 函数端点和 period.apply 的包装器,主要是为了方便。

    【讨论】:

      【解决方案2】:

      或者,您可以使用tapply 按周组申请。这里我使用lubridate 包从日期中提取星期部分。

      # fake data
      df <- structure(list(Datechar = c("2013-03-01", "2013-03-06", "2013-03-07", 
          "2013-03-12", "2013-03-13", "2013-03-15"), Kg = c(271L, 374L, 
          51L, 210L, 698L, 328L)), .Names = c("Datechar", "Kg"), class = "data.frame", row.names = c("1", 
          "2", "3", "4", "5", "6"))
      # convert character to date
      df$Date <- as.Date(df$Datechar)
      
      # calculate mean kg for each week
      library(lubridate)
      tapply(df$Kg, week(df$Date), mean)
      tapply(df$Kg, month(df$Date), mean)
      

      【讨论】:

        猜你喜欢
        • 2011-05-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 2020-09-16
        • 2021-11-03
        • 2017-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多