Create a list from binary time series

120 Views Asked by At

I have a simple binary time series, which lists if the USA is in a recession or not (https://fred.stlouisfed.org/series/USRECM) and I want to add it as a shaded region in a dygraph. However dygraphs only takes in a list (see link and below) so I need a quick an easy way to create a list of each recession period, which is marked by a 1.

Any efficient ways of doing this in R without me writing function that looks at current and lagged values.

    recession_periods <- list(
  list(from = "1920-1-1", to = "1930-1-1"),
  list(from = "1940-1-1", to = "1950-1-1"),
  list(from = "1960-1-1", to = "1970-1-1")
)
1

There are 1 best solutions below

0
On

Yes, with the 'seq' function for dates and the lubridate package. For instance, this will create a sequence of dates separated by 10 years.

library(data.table)
library(lubridate)

elements <- data.table(from = seq(from = as.Date('1920-01-01'), to = as.Date('1990-01-01'),by = "10 year"))
# Add the space in years between dates
elements[, to := from + years(10)]
finalList <- setNames(split(elements, seq(nrow(elements))), rownames(elements))

This will create something like this:

$`1`
         from         to
1: 1920-01-01 1930-01-01

$`2`
         from         to
1: 1930-01-01 1940-01-01

$`3`
         from         to
1: 1940-01-01 1950-01-01

$`4`
         from         to
1: 1950-01-01 1960-01-01

$`5`
         from         to
1: 1960-01-01 1970-01-01

$`6`
         from         to
1: 1970-01-01 1980-01-01

$`7`
         from         to
1: 1980-01-01 1990-01-01

$`8`
         from         to
1: 1990-01-01 2000-01-01

You can create many other pairs of dates, by different number of years, weeks, days, etc. using the by parameter in seq and the lubridate functions.