2

I know from Loop in R markdown that the asis parameter in a markdown chunk will print the output of a loop. I want to render the same designed table for several variables and can't seem to figure out how to do that when using knitr. In this example, I want to see three tables, each with one row of mtcars.

---
title: "Untitled"
author: "Matt"
date: '2022-08-13'
output: html_document
---

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


```{r, results = 'asis'}
for( i in 1:3 ){
 knitr::kable( mtcars[i,] , 
   caption = i ) %>%
   kable_paper( "hover" , full_width = F )
}
```

enter image description here

MatthewR
  • 2,660
  • 5
  • 26
  • 37

1 Answers1

2

One approach could be creating the expression for tables in the for loop as string literals then simply paste them with knitr::knit(text = ...)

```{r create_tables, include=FALSE}

multiple_tables <- rep("", 3)

for( i in 1:3 ){
  
  multiple_tables[i] <- paste0(
    "```{r echo=FALSE}\n",
    "knitr::kable( mtcars[", i, ",], caption = ", i, ") %>%
     kable_paper( \"hover\" , full_width = F )",
    "\n```\n"
  )
  
}

```


`r paste(knit(text = multiple_tables), collapse = '\n')`

shafee
  • 15,566
  • 3
  • 19
  • 47