seed <- 20250508
n_years <- 5
frequency <- 12
n_months <- n_years * frequency
base_seasonal_pattern <- c(-0.5, -0.6, 1.0, -0.3, -0.7, 2.0, -0.4, -0.5, -2.5, -0.2, -0.3, 3.0)
amplitude_scale_factors <- seq(from = 0.8, to = 5.2, length.out = n_years)
seasonal_component <- unlist(lapply(amplitude_scale_factors, function(scale_factor) {
scaled_pattern <- base_seasonal_pattern * scale_factor
scaled_pattern - mean(scaled_pattern)
}))
trend_component <- numeric(n_months)
trend_value <- 5
for (i in 0:(n_years - 1)) {
year_index <- (i * frequency + 1):((i + 1) * frequency)
end_value <- if (i %% 2 == 0) trend_value + 2 else trend_value - 2
trend_component[year_index] <- seq(from = trend_value, to = end_value, length.out = frequency)
trend_value <- end_value
}
set.seed(seed)
noise_component <- rnorm(n_months, mean = 0, sd = 0.5)
observed_data <- seasonal_component + trend_component + noise_component
set.seed(seed)
outlier_indices <- sample(1:n_months, 3)
outlier_magnitudes <- c(10, -12, 15)
observed_data[outlier_indices] <- observed_data[outlier_indices] + outlier_magnitudes
data_ts <- ts(observed_data, frequency = frequency, start = c(2020, 1))
true_trend_ts <- ts(trend_component, frequency = frequency, start = c(2020, 1))
true_seasonal_ts <- ts(seasonal_component, frequency = frequency, start = c(2020, 1))
y_range <- range(c(data_ts, true_trend_ts))
plot(data_ts,
main = "サンプルデータ", ylab = NULL,
ylim = c(y_range[1], y_range[2] + 0.2 * diff(y_range))
)
lines(true_trend_ts, col = "blue", lwd = 2)
points(time(data_ts)[outlier_indices], data_ts[outlier_indices],
col = "red", pch = 19, cex = 1.5
)
legend("topleft",
legend = c("観測データ", "真のトレンド", "外れ値"),
col = c("black", "blue", "red"), horiz = TRUE,
lty = c(1, 1, NA), pch = c(NA, NA, 19), lwd = c(1, 2, NA), cex = 0.8
)
abline(v = seq(2020, 2020 + n_years, by = 1), col = "grey", lty = 2)