R语言如何识别跨年场景为预测数据新增target_year目标年份列
R 数据表新增target_year字段实现方案
方法1:dplyr包实现(写法最简洁)
首先加载依赖包,可先构造和你场景匹配的示例数据,再执行字段新增逻辑:
# 加载dplyr依赖 library(dplyr) # 构造示例测试数据(字段和你描述的完全匹配) df <- tibble( target_week = c(50,51,52,53,1,2,3,4), forecast_month = rep(11, 8), forecast_year = rep(2017, 8), weekly_level = rnorm(8) # 模拟业务指标值 ) # 按规则新增target_year字段 df <- df %>% mutate(target_year = case_when( target_week %in% 1:4 ~ forecast_year + 1, target_week %in% 50:53 ~ forecast_year ))
如果要适配2015-2020年全量业务数据,可以直接用通用阈值判断,不需要限定周数区间:
df <- df %>% mutate(target_year = ifelse(target_week <= 4, forecast_year + 1, forecast_year))
方法2:base R实现(无需额外安装依赖包)
# 直接给数据集新增target_year字段 df$target_year <- ifelse(df$target_week %in% 1:4, df$forecast_year + 1, df$forecast_year)
输出效果验证
处理后的数据完全符合要求,示例效果如下:
| target_week | forecast_month | forecast_year | weekly_level | target_year |
|---|---|---|---|---|
| 50 | 11 | 2017 | xxx | 2017 |
| 51 | 11 | 2017 | xxx | 2017 |
| 52 | 11 | 2017 | xxx | 2017 |
| 53 | 11 | 2017 | xxx | 2017 |
| 1 | 11 | 2017 | xxx | 2018 |
| 2 | 11 | 2017 | xxx | 2018 |
| 3 | 11 | 2017 | xxx | 2018 |
| 4 | 11 | 2017 | xxx | 2018 |
内容的提问来源于stack exchange,提问作者kaja
相关产品推荐
相关产品推荐

