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

基于滑动窗口(窗口5、步长1)计算线性回归斜率的技术需求

滑动窗口计算线性回归斜率(窗口大小5,步长1)

需求说明

给定DataFrame,需实现:

  • 以5行为滑动窗口,每次窗口滑动1行
  • 对每个窗口内的mpg(因变量)和disp(自变量)计算线性回归的斜率
  • 末尾不足5行的位置填充NA

实现方案

推荐使用slider包(专门处理滑动窗口场景,代码简洁高效),也可以用dplyr+purrr组合实现。

方案1:使用slider包(推荐)

# 加载依赖包
library(dplyr)
library(slider)

# 对mtcars数据集计算滑动窗口斜率
mtcars_with_slope <- mtcars %>%
  mutate(
    slope = slide_dbl(
      .x = cur_data(),          # 当前数据集
      .f = ~ lm(mpg ~ disp, data = .x)$coefficients[["disp"]],  # 计算斜率的函数
      .before = 4,              # 窗口包含当前行 + 前4行,共5行
      .complete = TRUE          # 仅当窗口有完整5行时计算,否则返回NA
    )
  )

方案2:使用dplyr+purrr组合

如果不想额外安装slider包,可以用基础tidyverse工具实现:

library(dplyr)
library(purrr)

# 定义计算单个窗口斜率的函数
calc_slope <- function(window_df) {
  lm(mpg ~ disp, data = window_df)$coefficients[["disp"]]
}

# 生成滑动窗口并计算斜率
mtcars_with_slope <- mtcars %>%
  mutate(row_num = row_number()) %>%
  mutate(
    slope = map_dbl(
      # 生成有效窗口的起始索引,超出范围的位置设为NA
      ifelse(row_num <= n() - 4, row_num, NA),
      ~ if (!is.na(.x)) {
        # 提取对应窗口的数据集并计算斜率
        calc_slope(slice(mtcars, .x:(.x + 4)))
      } else {
        NA_real_
      }
    )
  ) %>%
  select(-row_num)  # 移除辅助列

验证示例

手动计算第1-5行的斜率:

mtcars[1:5, c("mpg", "disp")] %>% lm(mpg ~ disp, data = .)$coefficients[["disp"]]

对比mtcars_with_slope$slope[1],结果完全一致;同理,第2-6行的斜率对应mtcars_with_slope$slope[2],以此类推。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:19