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

如何在R语言中用同一函数不同参数批量生成多列?

批量生成分组滚动求和列

问题描述

给定以下R数据:

library(tidyverse)
library(slider)

data <- tibble::tribble(
  ~group, ~value,
  "0001",     2L,
  "0001",    -2L,
  "0001",     7L,
  "0001",    -9L,
  "0001",     2L,
  "0001",    -4L,
  "0001",     6L,
  "0001",   -10L,
  "0001",     4L,
  "0001",    -3L,
  "0002",    -2L,
  "0002",     5L,
  "0002",    -2L,
  "0002",     4L,
  "0002",    -2L,
  "0002",     2L,
  "0002",    -3L,
  "0002",     3L,
  "0002",    -1L,
  "0002",     5L,
  "0003",    -2L,
  "0003",     6L,
  "0003",   -19L,
  "0003",     2L,
  "0003",    -1L,
  "0003",     2L,
  "0003",    -2L,
  "0003",     2L,
  "0003",    -2L,
  "0003",     4L
  )

需要按group分组,生成不同前序行数的滚动求和列,手动实现需要逐个定义列:

data %>%
  group_by(group) %>%
  mutate(rolling1 = slide_sum(value, before = 1),
         rolling3 = slide_sum(value, before = 3),
         rolling5 = slide_sum(value, before = 5),
         rolling7 = slide_sum(value, before = 7),
         rolling9 = slide_sum(value, before = 9)) %>%
  ungroup()

现在希望批量生成这些列,避免重复代码,具体实现方法如下:

实现方法

方法1:使用map_dfc批量生成并合并列

这是最简洁的写法,通过map_dfc遍历所有需要的窗口大小,生成对应的滚动求和列,再统一命名后添加到原数据中:

# 定义需要的前序行数
window_sizes <- c(1, 3, 5, 7, 9)

data %>%
  group_by(group) %>%
  mutate(
    # 遍历窗口大小生成滚动求和列,合并为数据框后命名
    map_dfc(window_sizes, ~ slide_sum(value, before = .x)) %>%
      set_names(paste0("rolling", window_sizes))
  ) %>%
  ungroup()

方法2:使用命名函数列表结合!!!展开

先生成对应每个窗口大小的命名函数,再在mutate中展开批量生成列:

window_sizes <- c(1, 3, 5, 7, 9)

# 创建命名函数列表,每个函数对应一个窗口大小的滚动求和
rolling_functions <- set_names(
  map(window_sizes, ~ purrr::partial(slide_sum, before = .x)),
  paste0("rolling", window_sizes)
)

data %>%
  group_by(group) %>%
  mutate(!!!rolling_functions(value)) %>%
  ungroup()

方法3:使用across批量处理

通过across配合命名函数列表实现,适合需要统一处理多列的场景(这里仅针对value列):

window_sizes <- c(1, 3, 5, 7, 9)
col_names <- paste0("rolling", window_sizes)

data %>%
  group_by(group) %>%
  mutate(
    across(
      .cols = value,
      .fns = set_names(
        map(window_sizes, ~ function(x) slide_sum(x, before = .x)),
        col_names
      ),
      .names = "{.fn}"
    )
  ) %>%
  ungroup()

以上三种方法都能实现批量生成目标列,避免手动重复编写rollingX = ...的代码,其中方法1代码最简洁,适合单列的批量处理场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:57:54