R:如何处理亚小时数据的时间序列?

R: How to work with time series of sub-hour data?

我刚开始使用 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 不识别日期或时间,而是 "factor",我使用 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

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

"ts" class 通常不适合这种类型的数据。假设 DF 是本答案末尾注释中可重复显示的数据框,我们将其转换为 "zoo" class 对象,然后执行一些操作。也可以使用相关的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"))