【问题标题】:time series aggregation by month in RR中按月聚合的时间序列
【发布时间】:2018-09-24 16:59:02
【问题描述】:

在 mydataset 中,日期格式为日。我需要将其汇总为月份格式。 为了清楚起见,这里是 mydataset。

mydat
structure(list(date = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("12.01.2015", "13.01.2015", 
"14.01.2015", "15.01.2015"), class = "factor"), Y = c(200L, 50L, 
100L, 50L, 200L, 200L, 50L, 200L, 100L, 1000L, 1000L, 50L, 50L, 
100L, 200L)), .Names = c("date", "Y"), class = "data.frame", row.names = c(NA, 
-15L))

聚合必须是 Y 的总和。 在输出中我期望这种格式 01.2015 3550(2015年1月Y变量之和) 02.2015 4000(2015年2月Y变量之和)

怎么做? 我试着像这里Aggregate time series object by month R 那样做,但它对我没有帮助。 如何正确?

【问题讨论】:

    标签: r dataframe time-series


    【解决方案1】:

    我们创建一个带有年+月的分组变量,然后执行sum

    library(tidyverse)
    library(zoo)
    mydat %>%
       group_by(yearMon = as.yearmon(dmy(date))) %>% 
       summarise(Y = sum(Y))
    

    【讨论】:

    • 感谢您快速实用的回答
    【解决方案2】:

    这是使用aggregate 的基本 R 解决方案:

    with(mydat, aggregate(
        Y, 
        list(month_year = format(as.POSIXct(date, format = "%d.%m.%Y"), "%m/%Y")), 
        sum))
    #  month_year    x
    #1    01/2015 3550
    

    说明:从date 中提取month_year 组件,并使用month_yearYaggregate 相加。


    样本数据

    mydat <- structure(list(date = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L,
            3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("12.01.2015", "13.01.2015",
            "14.01.2015", "15.01.2015"), class = "factor"), Y = c(200L, 50L,
            100L, 50L, 200L, 200L, 50L, 200L, 100L, 1000L, 1000L, 50L, 50L,
            100L, 200L)), .Names = c("date", "Y"), class = "data.frame", row.names = c(NA,
            -15L))
    

    【讨论】:

    • 谢谢,你的回答也很有用:)
    【解决方案3】:

    1) data.frame 使用aggregate"yearmon" 类分组变量:

    library(zoo)
    
    fmt <- "%d.%m.%Y"
    aggregate(mydat["Y"], list(Date = as.yearmon(mydat$date, fmt)), sum)
    
    ##       Date    Y
    ## 1 Jan 2015 3550
    

    2) 动物园 您可以考虑使用时间序列表示而不是数据框。这使得许多时间序列操作更容易。这里我们使用read.zoomydat 转换为动物园对象。 fmt 来自上方。

    library(zoo)
    
    Y <- read.zoo(mydat, FUN = as.yearmon, format = fmt, aggregate = sum)
    

    给这个动物园对象:

    Y
    ## Jan 2015 
    ##     3550 
    

    虽然没有必要,但如果您想将其转换回数据框,请参阅?fortify.zoo

    3) xts/动物园

    转换为 xts 时间序列表示 x,然后使用 aggregate.zoo 创建动物园对象 zfmt 来自上方。

    library(xts)  # also pulls in zoo
    
    x <- xts(mydat["Y"], as.Date(mydat$date, fmt))
    z <- aggregate(x, as.yearmon, sum)
    z
    ## 
    ## Jan 2015 3550
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2018-02-28
      • 2014-12-15
      • 2018-06-24
      相关资源
      最近更新 更多