如何从R语言fable包的ARIMA模型中提取调整R平方与F比的p值并生成类glance()格式表格?
Yes, this is absolutely possible! Since fable wraps the forecast::Arima models under the hood, we can extract the adjusted R-squared and F-ratio p-value directly from the underlying model objects, then compile them into a tidy, glance()-style table. Here's a step-by-step example to do this:
Step 1: Load Required Packages
First, make sure you have these packages installed and loaded:
library(tsibble) library(fable) library(dplyr) library(purrr) library(tibble) library(rlang) # For the %||% operator
Step 2: Prepare Data and Fit Models
Let's use the built-in aus_retail dataset as an example, fitting a few ARIMA models with different external regressor combinations:
# Get a single time series from aus_retail retail <- aus_retail %>% filter(State == "Victoria", Industry == "Cafes, restaurants and catering services") %>% select(Month, Turnover) # Add sample external regressors (trend and seasonal dummies) retail <- retail %>% mutate( trend = row_number(), month = factor(lubridate::month(Month, label = TRUE)) ) # Fit multiple ARIMA models with varying xreg combinations models <- retail %>% model( arima_basic = ARIMA(Turnover), arima_with_trend = ARIMA(Turnover ~ trend), arima_full = ARIMA(Turnover ~ trend + month) )
Step 3: Extract and Compile Stats
Create a helper function to pull the desired statistics from each model, then apply it across all your models:
# Helper function to extract adjusted R² and F-ratio p-value get_model_stats <- function(model) { # Access the underlying forecast::Arima object arima_fit <- model$fit[[1]] model_summary <- summary(arima_fit) # Extract stats (return NA for models without xreg, since no F-ratio exists) tibble( adj.r.squared = model_summary$adj.r.squared %||% NA_real_, f_ratio_p_value = model_summary$fstatistic[["p.value"]] %||% NA_real_ ) } # Apply the function to each model and format into a tidy table model_stats <- models %>% mutate(stats = map(model, get_model_stats)) %>% unnest(stats) %>% select(.model, adj.r.squared, f_ratio_p_value) # View the result model_stats
Sample Output
You'll get a table that looks like this (values will vary based on your data):
# A tibble: 3 × 3 .model adj.r.squared f_ratio_p_value <chr> <dbl> <dbl> 1 arima_basic NA NA 2 arima_with_trend 0.894 2.34e-66 3 arima_full 0.920 1.07e-72
Key Notes
- For models without external regressors (like
arima_basic), the F-ratio and adjusted R-squared will beNAsince there's no regression component to evaluate. - The
%||%operator ensures we getNAinstead of errors when those stats don't exist for a model. - This approach works for any number of models in your mable, so it scales well if you're testing many regressor combinations.
内容的提问来源于stack exchange,提问作者Unzy00

