1

I am basically trying to do some calculations on US recessions. I downloaded data from FRED and it looks like this:

library(quantmod)
getSymbols("USREC",src="FRED")

1754 2001-01-01     0
1755 2001-02-01     0
1756 2001-03-01     0
1757 2001-04-01     1
1758 2001-05-01     1
1759 2001-06-01     1
1760 2001-07-01     1
1761 2001-08-01     1
1762 2001-09-01     1
1763 2001-10-01     1
1764 2001-11-01     1
1765 2001-12-01     0
1766 2002-01-01     0
1767 2002-02-01     0
1768 2002-03-01     0
1769 2002-04-01     0
1770 2002-05-01     0
1771 2002-06-01     0

Where 1 indicates a recession and 0 indicates non-recession (growth).

I want to calculate the mean length, max length and min length of the consecutive 1s. And the same with the 0s.

I want to do this in an elegant fasion. I was maybe thinking of converting the 0s to -1s and do some summarizing. I have searched a whole lot, and can't seem to find a good path to work by.

This thread gives some clues, but he is only plotting (as far as I can tell): R Recession Dates Conversion

Can someone point me in the right direction?

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
Cronos
  • 83
  • 1
  • 2
  • 6
  • Thanks! That solved my problem in a very elegant way! Is it also possible to show the associated dates/times (from the xts object) with the max/min values (either start, end or in the middle)? Just nice to have. Not need to have. Thanks again! – Cronos Jun 19 '17 at 19:21

1 Answers1

1

Let your_vector be that binary vector of recession / non-recession,

oo <- with(rle(your_vector), split(lengths, values))
sapply(oo, function(x) c(min = min(x), max = max(x), mean = mean(x)))

I am having trouble getting your data from quantmod and don't know why.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248