指标A_总计=指标A_北京+指标A_上海+指标A_广州....
数据源
dt | city_name | week_num | 指标A |
2022/12/6 | 北京 | 49 | 100 |
2022/12/6 | 上海 | 49 | 102 |
... | 49 | ||
2022/12/12 | 北京 | 50 | 98 |
2022/12/12 | 上海 | 50 | 105 |
... | ... | ... | ... |
问题:已经得到指标A_总计,第50周比第49周环比增长10%,现在需要得出单一城市的变动幅度对于整体影响最大的三个城市。
step1:数据导入
getwd()
setwd('/Users/tinawang/Documents/R/...')
data <- readxl::read_xlsx("文件名.xlsx")
head(data)
step2:分组汇总
因为每周一统计上周的数据,所以取上周和上上周的周数需要用到如下代码
#假设今天是周一,取上周周数
as.numeric(format(today()-1,"%W"))
将数据处理成如下格式:
city_name | after | before | 环比 |
上海 | 97 | 113 | -0.141652 |
合肥 | 19 | 28 | -0.2959711 |
广州 | 50 | 58 | -0.1260859 |
苏州 | 13 | 18 | -0.2982998 |
深圳 | 50 | 55 | -0.0922719 |
library(dplyr)
library(plyr)
all <- ddply(data,.(city_name,week_num),summarize,index=sum(指标A)/7)
a<- subset(all,week_num==as.numeric(format(today()-1,"%W")))
b<- subset(all,week_num==as.numeric(format(today()-1,"%W"))-1)
library(reshape)
library(reshape2)
a <- rename(a,c(index="after"))
b <- rename(b,c(index="before"))
temp <- merge(a,b,by=c("city_name"),all=TRUE)
data_变动趋势 <- subset(temp,select=c("city_name","after","before"))
data_变动趋势$环比 <- data_变动趋势$after/data_变动趋势$before-1
head(data_变动趋势)
step3:计算指标贡献度
#计算整体数据
all_city <- ddply(data,.(week_num),summarize,index=sum(指标A)/7)
#计算上周整体数据
all_after <- all_city$index[all_city$week_num==as.numeric(format(today()-1,"%W"))]
#计算上上周整体数据
all_before <- all_city$index[all_city$week_num==as.numeric(format(today()-1,"%W"))-1]
#计算贡献度
data_变动趋势$贡献度 <- ((data_变动趋势$after-data_变动趋势$before)/all_before)/(all_after/all_before-1)
#根据贡献度排序,取正向贡献最大的10个城市和负向贡献度最大的10个城市
data_变动趋势 <- data_变动趋势[order(-data_变动趋势$贡献度),]
head(data_变动趋势,10)
data_变动趋势 <- data_变动趋势[order(data_变动趋势$贡献度),]
head(data_变动趋势,10)
最终结果如下,以10个正向贡献度最大的城市为例:
city_name | after | before | 环比 | 贡献度 |
上海 | 97 | 113 | -0.141652 | 0.3798109 |
合肥 | 19 | 28 | -0.2959711 | 0.1934504 |
广州 | 50 | 58 | -0.1260859 | 0.1715057 |
苏州 | 13 | 18 | -0.2982998 | 0.1303174 |
深圳 | 50 | 55 | -0.0922719 | 0.1205267 |