The NBER dates recessions by their peak and trough. The json version of the data is here. A simple version looks like this:
list_old <- list(list(peak = "", trough = "1854-12-01"), list(peak = "1857-06-01", trough = "1858-12-01"))
In order for plotBands
to be displayed in the highcharter
package, the lists must be renamed so that "peak" becomes "start" and "trough" becomes "end". The resulting list would look like this:
list_new <- list(list(start = "", end = "1854-12-01"), list(start = "1857-06-01", end = "1858-12-01"))
Is there a way to achieve this using the tidyverse in R? (I've been looking in the purrr
package.)
CodePudding user response:
You can just use lapply
to rename each list.
lapply(list_old, \(x) {
names(x) <- c("start", "end")
x
}
)
#> [[1]]
#> [[1]]$start
#> [1] ""
#>
#> [[1]]$end
#> [1] "1854-12-01"
#>
#>
#> [[2]]
#> [[2]]$start
#> [1] "1857-06-01"
#>
#> [[2]]$end
#> [1] "1858-12-01"
You could use purrr::map()
if you'd rather a tidy solution. If using purrr
, from @Donald Seinen's comment, can also use set_names()
library(purrr)
map(
list_old,
set_names,
c("start", "end")
)
#> [[1]]
#> [[1]]$start
#> [1] ""
#>
#> [[1]]$end
#> [1] "1854-12-01"
#>
#>
#> [[2]]
#> [[2]]$start
#> [1] "1857-06-01"
#>
#> [[2]]$end
#> [1] "1858-12-01"