重采样与聚合观测

R 中的时间序列数据处理

Harrison Brown

Graduate Researcher in Geography

采样频率

频率:

  • 每年的观测次数
  • 如:每周、每日、每月…

时间分辨率:

  • "高分辨率":采样频繁
  • "低分辨率":采样稀疏
  • "高/低"具有主观性

概念图:两个网格,一个低分辨率,一个高分辨率,用于说明采样频繁与不频繁。

R 中的时间序列数据处理

聚合

  • 高分辨率 -> 低分辨率
  • 对所选区间应用 meansummax 等函数
  • 例如:
    • 将每日数据按月求 sum
    • 将每小时值按周求 mean
  • 无法"反向"聚合
  • 月总量 -> 每日值?
  • 提供描述数据模式的统计量
  • 聚合会丢失信息
R 中的时间序列数据处理

用 xts 聚合数据

xts

  • eXtensible Time Series(可扩展时间序列)
  • 扩展 zoo 包与 zoo
  • 提供 apply.*() 函数
yearly_mean <-
  apply.yearly(x = maunaloa,
               FUN = mean)
autoplot(yearly_mean) + 
  labs(...)

茂纳罗亚数据集按年聚合求平均后得到的图。不同于原始数据中每年强烈的波动,该图线条非常平滑,因为采样分辨率更低。

R 中的时间序列数据处理

用 xts 聚合数据

茂纳罗亚时间序列图,表示每周采样的二氧化碳浓度。整体呈上升趋势,每年有周期性季节峰值。

茂纳罗亚数据集按年聚合求平均后得到的图。不同于原始数据中每年强烈的波动,该图线条非常平滑,因为采样分辨率更低。

R 中的时间序列数据处理

apply 系列函数

daily_total <-
  apply.daily(hourly_sales,
              FUN = sum)
weekly_max <-
  apply.weekly(daily_temperature,
               FUN = max)
monthly_average <-
  apply.monthly(daily_price,
               FUN = mean)
apply.quarterly(sales_report,
                FUN = sum)
apply.yearly(monthly_salary,
             FUN = sum)
R 中的时间序列数据处理

Endpoints 与 period.apply

xts::endpoints()

xts::period.apply()

biweekly_eps <-
  endpoints(x = daily_data,
            on = "weeks",
            k = 2)
biweekly_data <-
  period.apply(x = daily_data,
               INDEX = biweekly_eps,
               FUN = mean)
biweekly_data
2002-05-05 8.148611
2002-05-19 8.146776
2002-06-02 8.060020
2002-06-16 8.028224
2002-06-30 7.944792
2002-07-14 7.930159
...
R 中的时间序列数据处理

Passons à la pratique !

R 中的时间序列数据处理

Preparing Video For Download...