lubridateの基本操作を習得したら、時系列データの統計分析と予測モデリングに挑戦しましょう。
ビジネスの未来を見据えた意思決定には、時系列の高度な分析技法が不可欠です。
⏰ 時系列の特徴量エンジニアリング
# 時系列特徴量エンジニアリング
library(tidyverse)
library(lubridate)
library(slider)
# 包括的な時系列特徴量作成
create_time_features <- function(data, date_col, value_col) {
data %>%
arrange({{date_col}}) %>%
mutate(
# 基本的な時間特徴量
year = year({{date_col}}),
month = month({{date_col}}),
weekday = wday({{date_col}}, label = TRUE),
is_weekend = wday({{date_col}}) %in% c(1, 7),
# 循環特徴量(正弦・余弦変換)
month_sin = sin(2 * pi * month / 12),
month_cos = cos(2 * pi * month / 12),
# 移動統計
ma_7 = slide_dbl({{value_col}}, mean, .before = 6),
ma_30 = slide_dbl({{value_col}}, mean, .before = 29),
# ラグ特徴量
lag_1 = lag({{value_col}}, 1),
lag_7 = lag({{value_col}}, 7),
# 差分特徴量
diff_1 = {{value_col}} - lag({{value_col}}, 1),
pct_change = ({{value_col}} - lag({{value_col}}, 1)) / lag({{value_col}}, 1) * 100
)
}
📊 季節性と異常値検出
# 季節性分析と異常値検出
library(forecast)
library(anomalize)
# 統計的異常値検出
detect_anomalies <- function(data, date_col, value_col) {
data %>%
mutate(
# 移動平均からの偏差
rolling_mean = slide_dbl({{value_col}}, mean, .before = 30),
rolling_sd = slide_dbl({{value_col}}, sd, .before = 30),
# Z-score方法
z_score = abs(({{value_col}} - rolling_mean) / rolling_sd),
is_anomaly = z_score > 3 & !is.na(z_score)
)
}
# 季節性分析
analyze_seasonality <- function(data, date_col, value_col) {
data %>%
group_by(month = month({{date_col}})) %>%
summarise(
avg_value = mean({{value_col}}, na.rm = TRUE),
seasonal_index = avg_value / mean(data[[quo_name(enquo(value_col))]], na.rm = TRUE),
.groups = "drop"
)
}
💡 実践的アドバイス
⏰ 時系列分析の成功法則
- データの質を確保:欠損値や異常値の適切な処理が精度を左右
- 季節性を理解:ビジネスサイクルや外部要因の影響を考慮
- 複数モデルを比較:単一モデルに依存せず、アンサンブルも検討
- 検証を徹底:時系列分割でのクロスバリデーションを実施
- 解釈しやすさを重視:ビジネス判断に活用できる説明可能性を確保
これらの時系列分析と予測モデリング技法により、データに基づいた将来予測と意思決定支援が可能になります。
次の章では、大容量データの効率的な読み込みと処理技法を学びましょう。