Is there a way to combine purr::map with a page break?

I am following code here to use the questionr package to generate some crosstabs in a report based on some surveys. My question is quite specific: Is there a way to combine the results that the call to map produces with some kind of newline command so that the resulting output is produced on its separate page?

---
title: "Test"
author: "Test"
date: "09/06/2021"
output: bookdown::pdf_document2
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F, results="hide", warning=F, message=F)
library(tidyverse)
library(questionr)
library(knitr)
```


```{r}
#Make data frame

Sex<-sample(c('low', 'high'), replace=T, size=100)
Income<-sample(c('male','female'), replace=T, size=100)
Vote<-sample(c("Liberal", "Conservative"), replace=T, size=100)
weight<-rnorm(n=100)
df<-data.frame(Sex, Income, weight, Vote)
```

```{r results="asis"}
#Want Tables By These variables
demos<-c("Sex", "Income")


```

```{r results="asis"}
#Print Crosstabs
demos %>% 
  map(., tabs, df=df, x="Vote") %>% 
  kable()

```

\newpage

# Desired Output
```{r page1, results="asis"}
kable(tabs(df, x="Vote", y="Sex"))
```

\newpage

# Second Page
```{r page2, results="asis"}
kable(tabs(df, x="Vote", y="Income"))

```

Hello Simon,
(probably) because I never use the library(tidyverse) statement I could not find the tabs function.
But I think you can adapt my circumvention of that function to fit your needs.

I create a chunk that generates only latex code and therefore use results='asis'.
This allow me to insert a \newpage statement.
In the kable function I indicate that the format should be latex.

```{r results='asis'}
demos %>%
  purrr::walk(., 
   function (col)
    {cat("\\newpage\n")
    cat(paste("report about ",col,"\n"))
    df1 <- df %>%
      dplyr::select (!!col, Vote,weight) %>%
      dplyr::group_by(!!col, Vote) %>%
      dplyr::summarise(weight=mean(weight))
      
    print(knitr::kable(df1,format='latex'))
    }
  ) 
```

This is possible but you would need to modify a bit your code. It will not be directly in the purrr::map call you made.

See several recipes in the R Markdown cookbook

This should help you.

basically, the steps should be

  • what the result should like ?
  • Make it a template (as text or in a file)
  • Iterate on that template to generate raw Rmd source
  • include as is in the doc

Hope it helps