Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you rename the elements of a list when they are nested within another list using R's purrr package?

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.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading