r - 某些条件下的累计
问题描述
我想对变量“nbre_lignes”进行累积总和,以便将结果变量命名为cumulative_sum,我设法做到了,但它不是自动的。有人可以帮我自动化吗?
library(FSA)
library(dplyr)
months.numeric <- lubridate:::months.numeric
strwr <- function(str) gsub(" ", "\n", str)
waterfall <- data.frame(table= strwr(c("Concaténation", "Doublons & NPI","DGC & CAR-REU", "BDD", paste("Répondants",format(as.yearqtr(Sys.Date()-base::months(12)),"T%q"), "&", format(as.yearqtr(Sys.Date()-months(9)),"T%q-%y")), paste("Sollicités au ", format(as.yearqtr(Sys.Date()-months(3)),"T%q-%y")), "Exclusions ", "QD", "Cible Finale")),
nbre_lignes=c(638334, -362769, -17674,41927,-1540, -20149, -300, -10, 19928))
#
waterfall$time <- 1:nrow(waterfall)
waterfall$flow <- factor(sign(waterfall$nbre_lignes))
waterfall$table <- factor(waterfall$table, levels = waterfall[["table"]])
b <- pcumsum(waterfall$nbre_lignes[1:3])
l <- pcumsum(waterfall$nbre_lignes[4:8])
cumulative_sum <- c(b,l, 0)
waterfall <- waterfall %>% cbind(cumulative_sum)
table nbre_lignes time flow cumulative_sum
1 Concaténation 638334 1 1 0
2 Doublons\n&\nNPI -362769 2 -1 638334
3 DGC\n&\nCAR-REU -17674 3 -1 275565
4 BDD 41927 4 1 0
5 Répondants\nT3\n&\nT4-18 -1540 5 -1 41927
6 Sollicités\nau\n\nT2-19 -20149 6 -1 40387
7 Exclusions\n -300 7 -1 20238
8 QD -10 8 -1 19938
9 Cible\nFinale 19928 9 1 0
解决方案
我们可以使用cumsum(flow == 1)
如下所示形成一个分组变量:
waterfall %>%
group_by(grp = cumsum(flow == 1)) %>%
mutate(cumsum = lag(cumsum(nbre_lignes), default = 0 )) %>%
ungroup %>%
select(- grp)
给予:
# A tibble: 9 x 5
table nbre_lignes time flow cumsum
<fct> <dbl> <int> <fct> <dbl>
1 Concaténation 638334 1 1 0
2 "Doublons\n&\nNPI" -362769 2 -1 638334
3 "DGC\n&\nCAR-REU" -17674 3 -1 275565
4 BDD 41927 4 1 0
5 "Répondants\nT3\n&\nT4-18" -1540 5 -1 41927
6 "Sollicités\nau\n\nT2-19" -20149 6 -1 40387
7 "Exclusions\n" -300 7 -1 20238
8 QD -10 8 -1 19938
9 "Cible\nFinale" 19928 9 1 0
推荐阅读
- amazon-ec2 - 如何在 ec2 ubuntu 14.04 上设置 gui 并使用 Remmina 从我的本地 ubuntu 计算机连接到它
- ruby - “每个...做”和“做”有什么区别
- json - 无法在逻辑应用中使用液体从内容 JSON 中检索数据
- android - Gradle build 突然失败,提示“无法获取未知属性 'testInstrum'...”
- dataframe - 如何将字符串变量作为条件传递给 DataFrame 过滤器?
- node.js - node.js express route:某些路由不起作用&未定义的路由起作用
- java - Java Hibernate 会话没有被正确终止
- selenium - 使用 multiCapabilities 时如何识别 jasmine 中的特定 selenium 浏览器?
- elm - 你如何初始化类型别名?
- ruby-on-rails - 【Rails】我无法从同一个表单创建或更新一些具有父、子和孙子关系的表