如何在R中处理时间序列NA值以构建办公室入住率ARIMA模型
First, let's break down why your original code threw that error: na.omit.ts removes entire time points with NA values, which creates gaps in your hourly time series. Both stl() and ARIMA models require regularly spaced time series (no missing intervals), so this approach breaks the sequence structure entirely.
Since your NA values correspond directly to national holidays where no one was in the office, the most logical and business-aligned fix is to replace those NAs with 0—this accurately reflects the real-world occupancy for those days. Here's how to implement this step-by-step:
1. Replace NAs with 0 (Recommended Approach)
This preserves the regular hourly interval of your time series while staying true to the actual occupancy context:
# Assume your time series object is named ts_data ts_data[is.na(ts_data)] <- 0
Once you've cleaned the data, you can successfully run stl() to decompose the time series:
plot(stl(ts_data, s.window = "periodic"))
2. Build Your ARIMA Model
With the cleaned time series, you can now train an ARIMA model (using auto.arima from the forecast package to automate parameter selection):
library(forecast) # Train the ARIMA model on the cleaned data arima_model <- auto.arima(ts_data) # Generate forecasts (example: predict 24 hours ahead) forecast_result <- forecast(arima_model, h = 24) # Visualize the forecast plot(forecast_result)
Alternative Methods (Not Recommended for Your Use Case)
For completeness, here are other NA-handling techniques—but they don't make sense for your specific scenario:
- Interpolation: Using
na.interp()to fill NAs with interpolated values would invent false occupancy numbers for holidays, distorting your model's understanding of real patterns. - Deleting NA intervals: As you saw firsthand, this breaks the regular time spacing required for ARIMA and STL, leading to errors and unreliable model outputs.
By replacing NAs with 0, you're not just fixing a technical error—you're ensuring your model learns the true occupancy patterns (including holiday zeros), which will make your forecasts far more accurate.
内容的提问来源于stack exchange,提问作者user12220606

