r - xts - 如何在一周中的每一天进行子集化

标签 r xts

我知道已经回答了类似的问题。我的问题是我有 2033 天的时间序列数据,间隔为 15 分钟。我想为每一天(周一至周日)绘制系列。例如,周一的平均情况。

我尝试使用 .indexwday 进行子集化,但当天的系列从 13:00 开始。

我是新手,所以如果我需要提供更多详细信息,请告诉我。

样本数据(xts)

  • 2008-01-01 00:00:00 16
  • 2008-01-01 00:15:00 56
  • 2008-01-01 00:30:00 136
  • 2008-01-01 00:45:00 170
  • 2008-01-01 01:00:00 132

....

  • 2013-07-25 22:30:00 95
  • 2013-07-25 22:45:00 82
  • 2013-07-25 23:00:00 66
  • 2013-07-25 23:15:00 65
  • 2013-07-25 23:30:00 66
  • 2013-07-25 23:45:00 46

下图可能更符合我的要求(这是所有星期一的平均值)

enter image description here

最佳答案

这是另一种解决方案,它不依赖于 xts 和 zoo 以外的包。

# example data
ix <- seq(as.POSIXct("2008-01-01"), as.POSIXct("2013-07-26"), by="15 min")
set.seed(21)
x <- xts(sample(200, length(ix), TRUE), ix)

# aggregate by 15-minute observations for each weekday
a <- lapply(split.default(x, format(index(x), "%A")),         # split by weekday
  function(x) aggregate(x, format(index(x), "%H:%M"), mean))  # aggregate by 15-min
# merge aggregated data into one zoo object, ordering columns
z <- do.call(merge, a)[,c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")]
# convert index to POSIXct to make plotting easier
index(z) <- as.POSIXct(index(z), format="%H:%M")
# plot
plot(z, type="l", nc=1, ylim=range(z), main="Average daily volume", las=1)

设置 ylim 强制每个绘图具有相同的 y 轴范围。否则它们将取决于每个单独的系列,如果值差异很大,这可能会使它们难以比较。

enter image description here

关于r - xts - 如何在一周中的每一天进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37224543/

相关文章:

r - Tornado 图/ggplot2 图表

r - 有没有办法在不调整透明度的情况下在 R 中显示重叠的直方图?

r - 条形图 - 添加百分比

删除具有连续相似数据的行 - R Zoo

r - 合并不同大小的xts对象

r - Excel 日期格式未正确导入到 R 中

r - 如何使用 xts 对象处理 TTR 库中的 'Series contains non-leading NAs'?

r - xts 操作在 candlesticks::CSPDoji() 中返回 NULL

r - 时区、期间。使用 R 在 xts 中应用

r - 在 R 上安装 xts 包时出错