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

使用map()和map2()执行回归并为数据框添加拟合值

解决方法

首先,你现有代码存在几个需要调整的点:

  • 过滤条件使用了Index < 1996.877,但需求是Index ≤ 1996.877,需要修正
  • 第一段代码仅生成了训练数据集(过滤后)的拟合值,而需求是将所有观测值的拟合值添加到原数据框中
  • map2重复传入过滤数据集的写法冗余,可简化优化

以下是完善后的完整代码,完全实现需求:

library(tidyverse)

# 1. 提取需要做回归的目标列名
target_cols <- df %>% select(-Index) %>% names()

# 2. 生成各列对应的回归公式列表
formulas <- target_cols %>% paste("~ Index") %>% map(as.formula)

# 3. 基于筛选后的数据集训练线性回归模型
models <- formulas %>% map(lm, data = df %>% filter(Index <= 1996.877))

# 4. 生成原数据框所有行的拟合值,整理为指定列名的数据框
fitted_df <- models %>%
  map(~ predict(.x, newdata = df)) %>%  # 对原数据的所有观测值预测
  set_names(str_c(target_cols, "_fitted")) %>%  # 设置列名为DAX_fitted等格式
  bind_cols()  # 转换为数据框格式

# 5. 将拟合值列合并到原数据框
df_with_fitted <- df %>% bind_cols(fitted_df)

代码说明:

  • 用target_cols统一管理目标列名,避免重复代码
  • 严格遵循需求中的Index ≤ 1996.877筛选条件训练模型
  • 通过predict(.x, newdata = df)生成所有观测值的拟合值,包括Index > 1996.877的行
  • 直接通过set_names设置符合要求的拟合值列名
  • 最后用bind_cols完成原数据框与拟合值数据框的合并

如果想基于你原有的两段代码逻辑整合,也可以使用以下写法:

# 修正并完善拟合值生成逻辑
fitted <- df %>% 
  select(-Index) %>% 
  names() %>% 
  paste(.,' ~ Index') %>%  
  map(as.formula) %>% 
  map(~ predict(lm(.x, data = df %>% filter(Index <= 1996.877)), newdata = df)) %>%
  set_names(str_c(., "_fitted")) %>%
  bind_cols()

# 合并到原数据框
df <- df %>% bind_cols(fitted)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:37:32