r - 根据 R 中的逐月变化计算基础效应
问题描述
假设我们有一个示例数据框df
,它是一个假的 CPI 数据,包含date
和MoM
列,我需要计算base_effect
并new_price_effect
基于它们:
date MoM base_effect new_price_effect
0 2019-01 1.010 NA NA
1 2019-02 1.010 NA NA
2 2019-03 1.010 NA NA
3 2019-04 1.010 NA NA
4 2019-05 1.010 NA NA
5 2019-06 1.010 NA NA
6 2019-07 1.010 NA NA
7 2019-08 1.010 NA NA
8 2019-09 1.010 NA NA
9 2019-10 1.010 NA NA
10 2019-11 1.010 NA NA
11 2019-12 1.010 NA NA
12 2020-01 1.015 1.115668 1.015000
13 2020-02 1.015 1.104622 1.030225
14 2020-03 1.015 1.093685 1.045678
15 2020-04 1.015 1.082857 1.061364
16 2020-05 1.015 1.072135 1.077284
17 2020-06 1.015 1.061520 1.093443
18 2020-07 1.015 1.051010 1.109845
19 2020-08 1.015 1.040604 1.126493
20 2020-09 1.015 1.030301 1.143390
21 2020-10 1.015 1.020100 1.160541
22 2020-11 1.015 1.010000 1.177949
23 2020-12 1.015 1.000000 1.195618
或者:
structure(list(date = c("2019-1-1", "2019-2-1", "2019-3-1", "2019-4-1",
"2019-5-1", "2019-6-1", "2019-7-1", "2019-8-1", "2019-9-1", "2019-10-1",
"2019-11-1", "2019-12-1", "2020-1-1", "2020-2-1", "2020-3-1",
"2020-4-1", "2020-5-1", "2020-6-1", "2020-7-1", "2020-8-1", "2020-9-1",
"2020-10-1", "2020-11-1", "2020-12-1"), MoM = c(1.01, 1.01, 1.01,
1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.015,
1.015, 1.015, 1.015, 1.015, 1.015, 1.015, 1.015, 1.015, 1.015,
1.015, 1.015)), class = "data.frame", row.names = c(NA, -24L))
的计算base_effect
基于以下公式:
即:要计算 的基础效应2020-06
,我们使用MoM(2019-07) * MoM(2019-08) * MoM(2019-09) * MoM(2019-10) * MoM(2019-11) * MoM(2019-12) = 1.061520
, for 2020-09
,MoM(2019-10) * MoM(2019-11) * MoM(2019-12) = 1.030301
是基于new_price_effect
:
即:计算 的新价格效应2020-04
,我们使用MoM(2020-01) * MoM(2020-02) * MoM(2020-03) * MoM(2020-04) = 1.061364
; 对于2020-06
,MoM(2020-01) * MoM(2020-02) * MoM(2020-03) * MoM(2020-04) * MoM(2020-05) * MoM(2020-06) = 1.093443
等
我们可以看到,对于base_effect
,MoM
上December
一年的 是固定的,而对于new_price_effect
,当年的是固定的MoM
。January
和the base effect of for each December is always 1.00.
我如何用 R 计算它们?谢谢。
参考:
解决方案
下面的代码给出了想要的结果。它基于cumprod(MoM)
按年份分组,还有一些额外的技巧
library(tidyverse)
library(lubridate)
df = df %>%
as_tibble() %>%
mutate(date=as.Date(date), year=year(date), month=month(date)) %>%
arrange(year,month)
warning("This only works if df is complete (no missing month). If not, first tidyr::complete()")
df = df %>% mutate(MoM_prev_year=lag(MoM, 12))
df = df %>%
group_by(year) %>%
mutate(
new_price_effect = cumprod(MoM),
base_effect = rev(cumprod(rev(MoM_prev_year)))/MoM_prev_year
) %>%
ungroup()
推荐阅读
- vba - Excel VBA过滤器复制并粘贴在单独工作表上最后使用的行下
- ios - Ionic 应用程序在 iOS 设备的第一个屏幕上冻结
- r - tidyverse:所有列组合的卡方
- php - 为什么 "if($_SESSION['count'] >= 3" 给我错误?
- python - 仅将数据框中的新值附加到熊猫中的另一个数据框
- swift - 当应用程序处于后台或终止状态时,如何找到用户位置?
- android - MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri) 返回 null
- sql - 在 SQL 中向表中添加相同的随机行
- iot - NodeMCU v1.0(ESP8266-12E)的Arduino草图没有编译错误,但在NodeMCU v1.0(ESP8266-12E)板上没有工作
- rest - 无法将相同的应用程序用于 REST 调用我在 Spring Boot 中为 SOAP 服务公开的内容