R语言基于sigma分组滚动值创建数据框融资日期新列的实现方法
R数据框自定义列实现方案
实现代码
你可以直接在mutate中按如下逻辑编写,依赖dplyr包即可实现:
library(dplyr) set.seed(111) df <- data.frame(id = c(1,1,3,4,5,6,2,7), fund.date = sample(seq(as.Date('2018/01/01'), as.Date('2021/01/01'), by="day"), 8), sigma = c(0,0,1,2,0,1,2,3)) # 完整管道操作 result <- df %>% # 生成first_funding_date的周期标签:每遇到sigma==0就新增分组 mutate(first_period = cumsum(sigma == 0), # 生成last_funding_date的周期标签:连续sigma==0归为同一周期开头 last_period = cumsum(sigma == 0 & lag(sigma, default = 1) != 0)) %>% # 按first分组计算first_funding_date group_by(first_period) %>% mutate(first_funding_date = first(fund.date)) %>% ungroup() %>% # 按last分组计算last_funding_date group_by(last_period) %>% mutate(last_funding_date = fund.date[which.max(sigma)]) %>% ungroup() %>% # 可选:删除辅助计算的分组列 select(-ends_with("period"))
以上代码输出的两个新列完全匹配你给出的示例结果:
first_funding_date值依次为"2019-05-22"、"2020-09-05"、"2020-09-05"、"2020-09-05"、"2019-11-30"、"2019-11-30"、"2019-11-30"、"2019-11-30"last_funding_date值依次为"2020-03-03"、"2020-03-03"、"2020-03-03"、"2020-03-03"、"2020-12-04"、"2020-12-04"、"2020-12-04"、"2020-12-04"
逻辑说明
- 如果需要调整
last_funding_date的计算范围为全局滚动而非按周期分组,可以把对应生成逻辑改为:mutate(last_funding_date = fund.date[cummax((sigma == cummax(sigma)) * row_number())]) - 如果需要连续的
sigma==0归为同一个first_funding_date周期,只需把first_period的生成逻辑和last_period保持一致即可。
内容的提问来源于stack exchange,提问作者spencergadd
相关产品推荐
相关产品推荐

