为什么R中使用map_dbl()实现滚动求和在两种场景下表现不一致?
问题原因
两段代码的group_by参数不一致是结果错误的根本原因:
- 第一段代码中
aux列所有值均为1,group_by(aux)相当于将整个数据集作为唯一分组,计算滚动求和时会使用所有行的日期和数值进行判断,结果自然正确 - 第二段代码错误将
group_by参数设为了facility_usd,该列每个值基本都是唯一的,相当于每行单独分为一组,计算滚动求和时只能取到当前行的数值,自然得到错误结果
修正后代码
如果需求是对全量数据计算无分组的3年滚动金额求和,直接删除错误的group_by(facility_usd)即可;如果确实需要按某个维度分组(比如按客户、行业等),替换为对应的分组字段即可。无分组的修正代码如下:
library(dplyr) library(lubridate) library(purrr) facilities <- structure(list(facilityid = c(11983L, 12937L, 12960L, 12927L, 14201L, 14200L, 13539L, 13543L, 13548L, 115930L, 115931L, 13542L, 13547L, 1243L, 13535L, 13538L, 13553L, 13534L, 13537L, 14047L, 897L, 13544L, 2410L, 62175L, 13540L, 13541L, 898L, 1059L, 13530L, 13531L), facilitystartdate = structure(c(4183, 4562, 5209, 5457, 5844, 5985, 6209, 6209, 6209, 6240, 6240, 6268, 6322, 6356, 6382, 6390, 6390, 6421, 6452, 6452, 6482, 6502, 6503, 6513, 6515, 6515, 6543, 6543, 6543, 6543), class = "Date"), facility_usd = c(122, 690, 800, 225, 58, 360, 70, 124.5, 200, 44.899425, 115.455663, 120, 173.4, 50, 32, 68.7, 465, 26.638, 48, 8.245, 50, 143.9, 525, 90, 50, 40, 30, 345, 10, 7.5)), row.names = c(169L, 201L, 202L, 200L, 348L, 347L, 261L, 265L, 270L, 3645L, 3646L, 264L, 269L, 4L, 258L, 260L, 272L, 257L, 259L, 346L, 1L, 266L, 7L, 1144L, 262L, 263L, 2L, 3L, 254L, 255L), class = "data.frame") facilities <- facilities %>% mutate(facilitystartdate = as.Date(facilitystartdate, format = "%Y-%m-%d")) %>% mutate(cum1 = purrr::map_dbl(facilitystartdate, ~ sum(facility_usd[ facilitystartdate > (. - months(36)) & facilitystartdate <= .]))) facilities <- facilities %>% select(facilityid, cum1) colnames(facilities)[2] <- "All_3Y_deals_USD"
如果你的数据量较大,可使用slider包的滚动计算函数代替purrr::map_dbl,运行效率会高很多。
内容的提问来源于stack exchange,提问作者Moz
相关产品推荐
相关产品推荐

