reverse key:value in nested list

236 views Asked by At

I'm setting up urls for a shiny app. A slice of the url-list is given below (url_patterns). In my app I use this list to navigate to a tab given a url. However, I also want to update the url if the active tab changes and for that I use url_list. There is a (clear) mapping between the two lists so I would rather only maintain one and use code to create the other. That would mean transforming url_patterns into url_list (or the other way around). I wrote a nested loop that converts url_list to url_patterns_re. It seems to work (i.e., url_patterns_re == url_pattern) but I wonder if there is a better/quicker solution.

url_patterns <- list(
  "base/single-mean/" = list("nav_radiant" = "Single mean", "tabs_single_mean" = "Summary"),
  "base/single-mean/plot/" = list("nav_radiant" = "Single mean", "tabs_single_mean" = "Plot"),
  "sample/sampling/"    = list("nav_radiant" = "Sampling"),
  "sample/sample-size/" = list("nav_radiant" = "Sample size")
)

url_list <- list("Single mean" =
                 list("tabs_single_mean" =
                      list("Summary" = "base/single-mean/",
                           "Plot" = "base/single-mean/plot/")),
                 "Sampling" = "sample/sampling/",
                 "Sample size"= "sample/sample-size/")

url_patterns_re <- list()
for (i in names(url_list)) {
  res <- url_list[[i]]
  if(!is.list(res)) {
    url_patterns_re[[res]] <- list("nav_radiant" = i)
  } else {
    tabs <- names(res)
    for (j in names(res[[tabs]])) {
      url <- res[[tabs]][[j]]
      url_patterns_re[[url]] <- setNames(list(i,j), c("nav_radiant",tabs))
    }
  }
}

all(unlist(url_patterns) == unlist(url_patterns_re))
0

There are 0 answers