r - How to detect start and end of constant periods? -
this question has answer here:
i'm trying plot recession shading periods in r. consider following example, recession periods recognized 1, , non-recession periods 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 me pick starting dates , ending dates of recession periods? expected output:
start end 1918-09-01 1919-03-01 1920-02-01 1920-05-01
similar question has been asked few years ago, think answer not able solve question.
data <- read.csv('recession.csv') # add new first , last row data, enable detection of change # in beginning , in end of 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 start , end of each recession period. # periods detected via built in diff function calculates # differences between consecutive values in 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)])
Comments
Post a Comment