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

按分组执行回归并提取studentized.residuals与预测值问题求助

问题:按Location分组拟合线性模型并添加预测值和学生化残差

我尝试在数据集上按Location分组运行线性模型Y ~ X1 + X2,目标是在原数据集中新增“predicted values”和“studentized_residuals”两列。以下代码能生成部分有效结果,但仅对第一个分组生效:

library("tidyverse")
library(broom)
df <- as.data.frame(dataset)
df$Y <- as.numeric(df$Y)
df$X1 <- as.factor(df$X1)
df$X2 <- as.factor(df$X2)

by_group <- group_by(df, location)
model <- do(by_group, augment(lm(Y ~ X1 + X2, data = .)))
df$predicted <- model$.fitted
df$stud_resids <- model$.std.resid  

数据集示例:

Location    Y   X1  X2
1           32  1   1
1           44  1   2
1           58  1   3
1           76  2   1
1           73  2   2
1           37  2   3
1           52  3   1
1           78  3   2
1           60  3   3
2           93  1   1
2           78  1   2
2           25  1   3
2           97  2   1
2           85  2   2
2           60  2   3
2           70  3   1
2           62  3   2
2           95  3   3

解决方案

原代码的核心问题有两个:

  1. 分组列名不匹配:数据集里的列是Location(首字母大写),但代码里用的是location(小写),导致分组逻辑错误。
  2. 直接赋值新列时,没有确保拟合结果和原数据集的行完全对应,容易出现错位。

以下两种修正方法均可解决问题:

方法1:使用group_modify

library(tidyverse)
library(broom)

# 数据预处理,统一列名格式并转换变量类型
df <- as.data.frame(dataset) %>%
  mutate(
    Y = as.numeric(Y),
    X1 = as.factor(X1),
    X2 = as.factor(X2),
    Location = as.factor(Location)
  )

# 分组拟合模型并合并结果
df_with_results <- df %>%
  group_by(Location) %>%
  group_modify(~ augment(lm(Y ~ X1 + X2, data = .x))) %>%
  ungroup() %>%
  rename(
    predicted = .fitted,
    stud_resids = .std.resid
  )

方法2:使用nest + map

library(tidyverse)
library(broom)

# 数据预处理(同上)
df <- as.data.frame(dataset) %>%
  mutate(
    Y = as.numeric(Y),
    X1 = as.factor(X1),
    X2 = as.factor(X2),
    Location = as.factor(Location)
  )

# 嵌套分组数据,拟合模型后展开结果
df_with_results <- df %>%
  group_by(Location) %>%
  nest() %>%
  mutate(
    model = map(data, ~ lm(Y ~ X1 + X2, data = .x)),
    augmented = map(model, augment)
  ) %>%
  select(-data, -model) %>%
  unnest(augmented) %>%
  rename(
    predicted = .fitted,
    stud_resids = .std.resid
  ) %>%
  ungroup()

两种方法都会自动将每个分组的拟合结果与原数据正确合并,确保所有分组的预测值和学生化残差都能对应到正确的行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:15:19