R语言分解2018年日度销售时间序列报错求助
Hey there! Let's get your sales forecasting script working properly. The error you're seeing happens because the decompose() and stl() functions expect a ts (time series) object with an explicitly defined frequency—right now you're passing a zoo object, which these functions can't interpret to find repeating cycles (like your weekly sales pattern).
What's Causing the Error?
decompose()andstl()rely on knowing the frequency of your time series (how often the pattern repeats). For daily data with weekly cycles, the frequency should be 7 (one week = 7 days).- Your
myzooobject is a zoo object, not a ts object. These decomposition functions don't work with zoo inputs directly.
Fixed Code Walkthrough
Here's the adjusted version of your script that resolves the error and keeps your forecasting workflow intact:
# Load required packages library(forecast) library(sweep) library(timetk) library(zoo) # Read the Data # First, read raw values and convert to a numeric vector sales_data <- scan("R Project/Dataset/MyData.txt") # Skip the leading "X" value from your data file sales_values <- sales_data[-1] # Create a ts (time series) object with daily frequency (7 days/week) # Start date: 2018-01-01, which is the 1st day of 2018 my_ts <- ts(sales_values, start = c(2018, 1), frequency = 7) # Inspect and plot the time series print(my_ts) plot(my_ts, xaxt = "n") # Add formatted date axis date_inds <- seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by = "day") Axis(date_inds, side = 1, at = seq(date_inds[1], tail(date_inds, 1) + 60, by = "1 months"), format = "%b %Y") # Decompose the time series (now works!) composition <- decompose(my_ts) plot(composition) # Plot decomposition components # STL decomposition (also works now) stl_result <- stl(my_ts, s.window = "periodic") plot(stl_result) # ARIMA forecasting fit <- auto.arima(my_ts) fore <- forecast(fit, h = 15, level = c(99.5)) # Plot the forecast with custom axis plot(fore, xaxt = "n") Axis(date_inds, side = 1, at = seq(date_inds[1], tail(date_inds, 1) + 60, by = "1 months"), format = "%b %Y")
Key Changes Made:
- Data Loading: Used
scan()to read raw numeric values, then removed the leading "X" from your data file. - ts Object Creation: Replaced the zoo object with a ts object, specifying
frequency = 7to tell R your data has a weekly cycle. This is what fixes the decomposition error. - Decomposition Functions: Now
decompose()andstl()can correctly identify the weekly pattern in your data, since they have the frequency information they need.
Quick Note on Zero Values
Since your 0s represent holidays/Sundays, you might want to consider handling them (e.g., replacing with NA or interpolating) if you want more accurate decomposition/forecasting—right now, those zeros will pull down the seasonal component estimates. But that's an optional next step once your basic workflow is working!
内容的提问来源于stack exchange,提问作者Joan

