You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中批量针对多产品运行stepwise线性回归?

单门店全产品批量逐步回归方案

1. 依赖包加载

先加载所需工具包:

library(dplyr)
library(plm)
library(MASS) # 用于stepAIC实现逐步回归,若偏好base::step可省略

2. 封装分析函数

将单门店内所有产品的分析逻辑打包成函数,一次调用即可处理该门店全部20种产品:

analyze_store_products <- function(store_data) {
  # 按产品分组执行回归分析
  store_results <- store_data %>%
    group_by(Product) %>%
    group_modify(function(product_df, product_key) {
      # 保持你原有的面板数据转换逻辑
      product_pdata <- pdata.frame(product_df, index = c("Product", "Time"))
      product_df_clean <- data.frame(product_pdata)
      
      # 构建全变量初始模型(替换为你的8个候选自变量完整列表)
      full_lm <- lm(Lift ~ Depth + Length + Copromotion + Category.Sales.On.Merch + Quality.Support.Binary + Var6 + Var7 + Var8,
                    data = product_df_clean)
      
      # 执行逐步回归(direction可选"both"/"forward"/"backward",trace=0关闭中间输出)
      step_model <- step(full_lm, direction = "both", trace = 0)
      
      # 返回产品对应的分析结果
      list(
        Product = product_key$Product,
        Model_Summary = summary(step_model),
        Selected_Variables = names(coef(step_model))[-1] # 剔除截距项,仅保留入选自变量
      )
    }) %>%
    ungroup()
  
  return(store_results)
}

3. 单门店手动执行

每次仅需指定目标门店,调用函数即可得到该门店所有产品的分析结果:

# 筛选目标门店数据(替换为你要分析的门店名称)
target_store <- subset(your_raw_data, Store == "Store 1")

# 运行批量分析
store_analysis_results <- analyze_store_products(target_store)

# 查看单个产品结果示例
store_analysis_results$Model_Summary[store_analysis_results$Product == "Product 1"]

# 导出入选自变量列表到CSV(方便复盘)
write.csv(select(store_analysis_results, Product, Selected_Variables), 
          "Store1_Regression_Output.csv", row.names = FALSE)

关键说明

  • 请将代码中的Var6 + Var7 + Var8替换为你实际的另外3个候选自变量
  • 若需要查看逐步回归的变量筛选过程,将trace=0改为trace=1即可
  • store_analysis_results数据框包含每个产品的模型汇总和最终入选变量,可直接用于后续分析或报告

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:05:38