2

I am trying to create a nested tabset ideally using purrr::walk2. But something is missing in how I am creating the tabsets as the h2 tabs aren't joining. Here is a rmd reprex. Any way to do this in rmarkdown?

---
title: "nested-tabs"
output: html_document
date: "2022-08-25"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(purrr)
library(dplyr)
library(glue)

knitr::opts_chunk$set(echo = FALSE)
```

```{r}
starwars <- starwars %>% 
  head(5)

levels <- starwars %>% 
  distinct(sex, homeworld)
```

# Messy output 
```{r results='asis'}
walk2(levels$sex, levels$homeworld, ~{
    cat(
    glue(
      "\n## <<.x>> {.tabset}",
      .open = "<<",
      .close = ">>"
    ),
    "\n"
  )
  
  cat(glue("\n### {.y}"), "\n")
  
  starwars %>% 
    filter(sex == .x, homeworld == .y)
})
```

# Desired output
```{r results='asis'}
walk(levels$sex, ~{
    cat(
    glue(
      "\n## <<.x>> {.tabset}",
      .open = "<<",
      .close = ">>"
    ),
    "\n"
  )
  
  sw_tmp <- starwars %>% 
    filter(sex == .x)
  
  walk(levels$homeworld, ~{
  cat(glue("\n### {.x}"), "\n")
  
  starwars %>% 
    filter(homeworld == .x)
  })
})
```
boshek
  • 4,100
  • 1
  • 31
  • 55

1 Answers1

1

The problem is that purrr::walk2() is not equivalent to two nested purrr::walk()s. See this small example for instance:

library(purrr)

walk(c("A", "B"), ~{
  print(paste(.x, "---"))
  walk(1:2, ~{
    print(paste(.x, "-"))
  })
})
#> [1] "A ---"
#> [1] "1 -"
#> [1] "2 -"
#> [1] "B ---"
#> [1] "1 -"
#> [1] "2 -"

walk2(c("A", "B"), c(1:2), ~{
  print(paste(.x, "---"))
  print(paste(.y, "-"))
})
#> [1] "A ---"
#> [1] "1 -"
#> [1] "B ---"
#> [1] "2 -"

Created on 2022-08-26 by the reprex package (v2.0.1)

walk2() takes the first element of .x and .y for the first iteration, the second element of .x and .y for the second iteration, etc. This is why only one tab appears in your "messy" section.

You can't just replace the nested walk() (or nested for loops) with walk2(). Here are some solutions on how to replace these nested loops with purrr, but I think that the solution you already have is clean enough compared to them.

bretauv
  • 7,756
  • 2
  • 20
  • 57