如何检测恒定周期的开始和结束? [英] How to detect start and end of constant periods?

查看:44
本文介绍了如何检测恒定周期的开始和结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to plot recession shading periods in R. Consider the following example, where 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 dates and ending dates of the recession periods? Expected output:

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

类似的问题 几年前有人问过,但我认为答案不是能够解决这个问题.

Similar question has been asked a few years ago, but I think the answer is not able to solve this question.

推荐答案

data <- read.csv('recession.csv')

# Add new first and last row to the data, to enable the detection of change
# in the beginning and in the end of the time series.
data <- rbind(c(NA, ifelse(data$Recession[1] == 1, yes = 0, no = NA)),
              data,
              c(NA, ifelse(data$Recession[length(data$Recession)] == 1, 0, NA)))

# Create new data frame containing the start and end of each recession period.
# The periods are detected via built in diff function which calculates 
# differences between all consecutive values in a vector.
recession.periods <- data.frame(
    Start = data$Date[which(diff(data$Recession, lag = 1) == 1) + 1],
    End = data$Date[which(diff(data$Recession, lag = 1) == -1)])

这篇关于如何检测恒定周期的开始和结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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