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

如何基于x1、x2创建类似var5的累积比率列?

基于x1和x2的累积值计算比例生成新列

你需要的是计算x1的累积和与x2的累积和的比值,对应每一行的结果和示例中的var5一致。以下是两种在R中实现的方法:

示例数据

首先加载你的示例数据:

df <- structure(list(qtile = structure(1:5, levels = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", 
"27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", 
"38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", 
"49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", 
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", 
"71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", 
"82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", 
"93", "94", "95", "96", "97", "98", "99"), class = "factor"), 
    p = c(0.563602980118794, 0.563602980118794, 0.563602980118794, 
    0.563602980118794, 0.563602980118794), x1 = c(7723, 5023, 
    5309, 4820, 4731), x2 = c(10432, 6193, 6583, 6073, 5888), 
    var5 = c(0.7403183, 0.7666767, 0.7779645, 0.7812233, 0.7849527
    ), var6 = c(0.740318251533742, 0.811077022444696, 0.806471213732341, 
    0.793676930676766, 0.803498641304348)), row.names = c(NA, 
5L), class = "data.frame")

方法1:基础R实现

利用cumsum()函数计算累积和,直接生成新列:

# 计算累积x1和累积x2的比值
df$new_var5 <- cumsum(df$x1) / cumsum(df$x2)

# 查看结果
print(df)

运行后new_var5的数值会和原var5完全匹配,比如第2行结果为(7723+5023)/(10432+6193) = 12746/16625 ≈ 0.7666767,和示例一致。

方法2:dplyr包实现

如果你习惯使用tidyverse风格的管道操作,可以用dplyr的mutate()函数:

library(dplyr)

df <- df %>%
  mutate(new_var5 = cumsum(x1) / cumsum(x2))

该方法逻辑和基础R一致,只是写法更简洁,适合处理复杂的数据操作流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:20:46