R选择衰退期的开始日期和结束日期 [英] R pick up the starting date and ending date of the Recession period

查看:105
本文介绍了R选择衰退期的开始日期和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中绘制衰退期.请考虑以下示例,衰退期被识别为1,而非衰退期为0.

I'm trying to plot the Recession Shading periods in R. Consider the following example, recession periods are recognized as 1, and non recession periods are 0.

Date           Recession  
1918-09-01     1  
1918-10-01     1  
1918-11-01     1  
1918-12-01     1  
1919-01-01     1  
1919-02-01     1  
1919-03-01     1  
1919-04-01     0  
1919-05-01     0  
1919-06-01     0  
1919-07-01     0  
1919-08-01     0  
1919-09-01     0  
1919-10-01     0  
1919-11-01     0  
1919-12-01     0  
1920-01-01     0  
1920-02-01     1  
1920-03-01     1  
1920-04-01     1  
1920-05-01     1  

有人可以帮助我掌握经济衰退期的开始日期和结束日期吗?例如:

Can anyone help me to pick up the starting date and ending dates of the recession periods? For example:

Start                 End
1918-09-01     1919-03-01
1920-02-01     1920-05-01

几年前,有人问过同样的问题,但我认为答案不能解决这个问题.参见 R衰退日期转换

The same question has been asked few years ago, but I think the answer is not able solve this question. see R Recession Dates Conversion

提前谢谢!

推荐答案

使用data.table包中的rleid()函数:

library(data.table)
data.table(DF)[, .(min(Date), max(Date)), by = .(rleid(Recession), Recession)][
  Recession == 1, .(Start = V1, End = V2)]

        Start        End
1: 1918-09-01 1919-03-01
2: 1920-02-01 1920-05-01

说明

第一个data.table表达式可找到所有期间的开始和结束日期. rleid()是一种便捷功能,用于生成要在分组操作中使用的游程长度类型id列.

Explanation

The first data.table expression finds start and end dates of all periods. rleid() is a convenience function for generating a run-length type id column to be used in grouping operations.

data.table(DF)[, .(min(Date), max(Date)), by = .(rleid(Recession), Recession)]

   rleid Recession         V1         V2
1:     1         1 1918-09-01 1919-03-01
2:     2         0 1919-04-01 1920-01-01
3:     3         1 1920-02-01 1920-05-01

第二个表达式仅选择衰退期,并返回StartEnd日期.

The second expression picks only the Recession periods and returns the Start and End dates.

DF <- readr::read_table(
  "Date           Recession  
  1918-09-01     1  
  1918-10-01     1  
  1918-11-01     1  
  1918-12-01     1  
  1919-01-01     1  
  1919-02-01     1  
  1919-03-01     1  
  1919-04-01     0  
  1919-05-01     0  
  1919-06-01     0  
  1919-07-01     0  
  1919-08-01     0  
  1919-09-01     0  
  1919-10-01     0  
  1919-11-01     0  
  1919-12-01     0  
  1920-01-01     0  
  1920-02-01     1  
  1920-03-01     1  
  1920-04-01     1  
  1920-05-01     1  "
)

这篇关于R选择衰退期的开始日期和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆