【问题标题】:Cumulative sum on preceding rows in the same column - R同一列中前几行的累积和 - R
【发布时间】:2021-04-16 14:27:44
【问题描述】:

数据:

    test <- structure(list(fgu_clms = c(14621389.763697, 145818119.352026, 
21565415.2337476, 20120830.8221406, 12999772.0950838), loss_to_layer = c(0, 
125818119.352026, 1565415.23374765, 120830.822140567, 0)), row.names = c(NA, 
5L), class = "data.frame")

    > test
   fgu_clms loss_to_layer
1  14621390           0.0
2 145818119   125818119.4
3  21565415     1565415.2
4  20120831      120830.8
5  12999772           0.0

我想创建一个新列,尝试对其上方的行使用累积和。如果我逐行展示新列的计算方式会更容易:

row 1:首先计算同一列中以上行的值的总和。由于这是第 1 行,因此没有高于此值为 0 的行,将其称为 cumsum_1。然后它应该取“loss_to_layer”列中第 1 行的值和计算“x2 - cumsum_1”中的最小值。

在第 2 行:通过查看上面的值来计算 cumsum,即 min(x2-cumsum_1,loss_to_layer value)。将此称为 cumsum_2。然后如上重复,即以 loss-to_layer 列第 2 行的值和 x2 - cumsum_2 的最小值为准。

等等。

在 excel 中,这将通过使用 MIN(B2,x2 - SUM(C$1:C1)) 并向下拖动此公式来完成。

x2 = 127,000,000 的结果应该是:

   fgu_clms loss_to_layer   new_col
1  14621390           0.0         0
2 145818119   125818119.4 125818119
3  21565415     1565415.2   1181881
4  20120831      120830.8         0
5  12999772           0.0         0

如您所见,“new_col”的总和总是返回“x2”,在本例中为 127,000,000。

我试过了:

test <- test %>% mutate(new_col = pmin(loss_to_layer,127e6-cumsum(lag(new_col,1,default=0))))

但由于在滞后函数中找不到列 new_col 会出错

【问题讨论】:

  • @akrun 对不起,你是什么意思
  • @akrun 是的,这就是问题所在 - 这只是我的尝试,但我希望使用查看上面行的值创建 new_col,但我不确定我该怎么做。跨度>

标签: r


【解决方案1】:
test %>% 
  mutate(
    cumsum_1 = cumsum(lag(loss_to_layer, default = 0)),
    new_col = pmin(loss_to_layer, 127000000 - cumsum_1),
    new_col = ifelse(new_col < 0, 0, new_col)
  ) %>%
    select(-cumsum_1)

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多