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

如何对data.frame指定列做行向累积求和后按行除以Spend列?

R语言实现行向累积求和并按列缩放

首先构造你提供的原始数据框:

df <- data.frame(
  New_Sign_ups = c(100, 50),
  Spend = c(100, 200),
  `2021-05` = c(0, 10),
  `2021-06` = c(10, 10),
  `2021-07` = c(100, 40),
  MRR_sum = c(110, 60),
  time = c(1.5, 1.8)
)

下面提供两种常用实现方式:

方法一:基础R原生代码

无需额外依赖包,直接用矩阵操作完成:

# 提取第3到第5列的数值矩阵
target_matrix <- df[, 3:5]
# 对每行做累积求和,再除以对应行的Spend值
processed_matrix <- t(apply(target_matrix, 1, function(row_vals) cumsum(row_vals) / df$Spend))
# 将处理结果替换回原数据框的对应列
df[, 3:5] <- processed_matrix

方法二:tidyverse工具链(dplyr+purrr)

如果习惯用tidy风格代码,这种方式更直观易读:

library(dplyr)
library(purrr)

df <- df %>%
  mutate(
    # 对指定列逐行做累积求和后除以Spend
    across(`2021-05`:`2021-07`, ~ accumulate(.x, `+`) / Spend)
  )

运行后得到的最终结果如下:

df
#>   New_Sign_ups Spend 2021-05 2021-06 2021-07 MRR_sum time
#> 1          100   100    0.00     0.1     1.1     110  1.5
#> 2           50   200    0.05     0.1     0.3      60  1.8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:03:36