2017-07-28 6 views
1

誰も私を拾うのを助けることができる私は、景気後退期間は1として認識され、非景気後退期間は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 

されている次の例を考えてみR.に不況の影の期間をプロットしようとしています不況期の開始日と終了日?予想される出力:

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

Similar questionは数年前に頼まれましたが、私は答えはこの質問を解決することができないと思います。

+0

あなたはまだ '?rle'を見ましたか? –

答えて

2
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)]) 
関連する問題