【问题标题】:R: How to work with time series of sub-hour data?R:如何处理次小时数据的时间序列?
【发布时间】:2016-11-04 17:11:50
【问题描述】:

我刚开始学习 R 并完成了一些教程。但是,我正在尝试进行时间序列分析,但遇到了很大的麻烦。我做了一个看起来像这样的数据框:

    Date        Time        T1
 1  2014-05-22  15:15:00    21.6
 2  2014-05-22  15:20:00    21.2
 3  2014-05-22  15:25:00    21.3
 4  2014-05-22  15:30:00    21.5
 5  2014-05-22  15:35:00    21.1
 6  2014-05-22  15:40:00    21.5

由于我不想工作半天,我从数据框中删除了第一天和最后一天。由于 R 没有识别日期和时间,而是作为“因素”,我使用 lubridate 库来正确更改它。现在看起来像这样:

    Date        Time    T1
1   2014-05-23      0S  14.2
2   2014-05-23  5M 0S   14.1
3   2014-05-23  10M 0S  14.6
4   2014-05-23  15M 0S  14.3
5   2014-05-23  20M 0S  14.4
6   2014-05-23  25M 0S  14.5

现在麻烦真的开始了。使用 ts 函数将日期更改为 16944 并将时间更改为 0。如何设置具有正确开始日期和频率的数据框?每 5 分钟出现一组新数据,因此频率应为 288。我还尝试将开始日期设置为向量。由于 5 月 22 日是一年中的第 142 天,我尝试了这个

ts_df <- ts(df, start=c(2014, 142/365), frequency=288) 

那里没有错误,但是当我选择start(ds_df) 时,我得到了end(ds_df)

[1] 2013.998
[1] 2058.994

谁能告诉我如何处理这些数据?

【问题讨论】:

    标签: r time statistics time-series series


    【解决方案1】:

    "ts" 类通常不适合该类型的数据。假设 DF 是在此答案末尾的注释中可重现地显示的数据框,我们将其转换为 "zoo" 类对象,然后执行一些操作。也可以使用相关的xts包。

    library(zoo)
    
    z <- read.zoo(DF, index = 1:2, tz = "")
    
    window(z, start = "2014-05-22 15:25:00")
    
    head(z, 3) # first 3
    head(z, -3) # all but last 3
    tail(z, 3) # last 3
    tail(z, -3) # all but first 3
    
    z[2:4] # 2nd, 3rd and 4th element of z
    
    coredata(z) # numeric vector of data values
    time(z) # vector of datetimes
    
    fortify.zoo(z) # data frame whose 2 cols are (1) datetimes and (2) data values
    
    aggregate(z, as.Date, mean) # convert to daily averaging values
    
    ym <- aggregate(z, as.yearmon, mean) # convert to monthly averaging values
    frequency(ym) <- 12 # only needed since ym only has length 1
    as.ts(ym) # year/month series can be reasonably converted to ts
    
    plot(z)
    
    library(ggplot2)
    autoplot(z)
    

    read.zoo 也可以用于从文件中读取数据。

    注意:DF 以可重复的形式在上面使用:

    DF <- structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2014-05-22", 
    class = "factor"), 
        Time = structure(1:6, .Label = c("15:15:00", "15:20:00", 
        "15:25:00", "15:30:00", "15:35:00", "15:40:00"), class = "factor"), 
        T1 = c(21.6, 21.2, 21.3, 21.5, 21.1, 21.5)), .Names = c("Date", 
    "Time", "T1"), class = "data.frame", row.names = c("1", "2", 
    "3", "4", "5", "6"))
    

    【讨论】:

    • 您好格洛腾迪克,感谢您的快速回复。我花了一段时间才再次回复,但你帮了很多忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2021-12-13
    • 2013-12-07
    • 2013-09-16
    • 2012-07-01
    • 2020-03-25
    相关资源
    最近更新 更多