reactable in R markdown `asis` chunk with loop not displayed - r

I want to create dynamic sections in my R markdown document. For this, I use R chunks with the asis output type. The chunks contain tables created by the reactable package.
I cannot get the tables to print when I create them in a for-loop. I know that one usually must wrap plots or the like within print() in loops, but that had no effect in my case.
How can I get the tables to print?
---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---
```{r include=FALSE}
library(reactable)
```
```{r results='asis', echo=FALSE}
cat("\n\n## My header 1 \n\n")
reactable(data.frame(test = rnorm(3))) ## This works
```
```{r results='asis', echo=FALSE}
for (i in 1:3) {
cat("\n\n## My header ", i+1, "\n\n")
print(reactable(data.frame(test = rnorm(3)))) ## shows nothing
}
```

I just found out, that reactable uses htmlwidgets under the hood. So one can wrap the result in shiny::tagList() to display it in a loop.
---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---
```{r include=FALSE}
library(reactable)
```
```{r results='asis', echo=FALSE}
cat("\n\n## My header 1 \n\n")
reactable(data.frame(test = rnorm(3))) ## This works
```
```{r results='asis', echo=FALSE}
for (i in 1:3) {
cat("\n\n## My header ", i+1, "\n\n")
print(shiny::tagList(reactable(data.frame(test = rnorm(3))))) ## now it works
}
```

You could try to export your react-tables as temporary html-files that you then import as text and delete afterwards.
Here is a solution that worked for me:
---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---
```{r include=FALSE}
library(reactable)
```
```{r results='asis', echo=FALSE}
cat("\n\n## My header 1 \n\n")
reactable(data.frame(test = rnorm(3))) ## This works
```
```{r results='asis', echo=FALSE}
for (i in 1:3) {
cat("\n\n## My header ", i+1, "\n\n")
htmlwidgets::saveWidget(reactable(data.frame(test = rnorm(3))),
file = 'temp.html')
cat(readr::read_lines('temp.html')[-1])
file.remove('temp.html')
}
```

Related

R chunk inside LaTeX in an rmarkdown document

I am trying to get an R chunk run inside LaTeX code in the following rmarkdown document:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
```{r}
x <- 2+3
x
```
}
\end{enumerate}
The output is:
But I want:
Could you please help me?
EDIT: I want the R chunk to be both evaluated (but result hidden) and its code shown. I have meanwhile found this solution, but maybe there is a simpler one: https://tex.stackexchange.com/questions/210003/how-can-i-nest-a-code-chunk-within-an-enumerate-environment-when-using-r-markdow
You need this? See here https://bookdown.org/yihui/rmarkdown-cookbook/raw-latex.html
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
```{=latex}
\begin{tabular}{ll}
x <- 2+3\\
x\\
\end{tabular}
```
In any of the following examples, you can substitute a double return instead of \\.
If you are wanting to just show those expressions then do not put it in a code chunk:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
x <- 2 + 3\\x
}
\end{enumerate}
This will produce:
Otherwise, if you want to evaluate an inline expression use backticks and r:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
`r x <- 2 + 3; x`
}
\end{enumerate}
Which produces:
Lastly, you can of course combine these two concepts to show the expression and evaluate the value by doing this:
x <- 2 + 3\\
`r x <- 2 + 3; x`
If your expression is more complex, I would recommend having the code chunk outside of your LaTeX for evaluation.
Update
For simpler expressions you could do something like:
```{r, include = F}
exprsn <- "x <- 2 + 3"
```
\begin{enumerate}
\item
{
`r exprsn`\\
`r eval(parse(text = exprsn)); x`
}
\end{enumerate}
Meanwhile, I found this: How can I nest a code chunk within an enumerate environment when using R Markdown?, which inspires the following solution:
---
title: "Untitled"
output:
pdf_document:
highlight: monochrome
date: '2022-05-20'
header-includes:
- \newcommand{\benum}{\begin{enumerate}}
- \newcommand{\eenum}{\end{enumerate}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\benum
\item
```{r}
x <- 2+3
x
```
\eenum

RMarkdown is not referencing tables

Somehow my RMarkdown document is not crossreferencing tables or figures. Here is a stripped down version of my document.
---
title: "Test"
author: "Me"
date: "01/04/2022"
output: bookdown::pdf_document2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
var1<-sample(LETTERS)
tab1<-table(var1)
My table is in Table \#ref{tab:tab1}
library(knitr)
kable(tab1, caption="my table")
AS we see in Figure \#ref{fig:plot1}
plot(seq(1,10,1))
You should call your tab1 in the code chunk like this {r tab1}. And use () instead of {} for your #ref. In that case it reference to your figures and tables. You can use the following code:
---
title: "Test"
author: "Me"
date: "01/04/2022"
output: bookdown::pdf_document2
---
My table is in Table \#ref(tab:tab1)
```{r tab1, echo =FALSE}
var1<-sample(LETTERS)
tab1<-table(var1)
library(knitr)
kable(tab1, caption="my table")
```
\newpage
AS we see in Figure \#ref(fig:plot1)
```{r plot1, fig.cap ="plot", echo=FALSE}
par(mar = c(4, 4, .2, .1))
plot(seq(1,10,1))
```
Output:
As you can see on the image, when you click on 1 in will go to your table.

Rmarkdown not rendering raw HTML

After upgrading Rstudio to 1.4 version, when I render this rmarkdown doc
---
title: "Raw HTML"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
library(htmltools)
knitr::opts_chunk$set(echo = F)
```
```{r}
f <- function(text){
cat(asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>"))))
return(0)
}
```
```{r}
x <- f('Hello!')
```
I get this html doc
But before the update this code worked as expected, rendering this html doc
How can I get the second html doc?
cat removes the knit_asis class.
You can either avoid cat or use results='asis' chunck option :
---
title: "Raw HTML"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
library(htmltools)
knitr::opts_chunk$set(echo = F)
```
```{r}
side.effect <- function(text){
cat(asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>"))))
return(0)
}
direct <- function(text){
asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>")))
}
```
```{r}
direct('direct Hello!')
```
```{r,results ='asis'}
x <- side.effect('side effect Hello!')
```

Displaying data frame in r markdown

I want to have table in 'one line' instead of dividing it. In the second picture is what I get and in the first picture is what I want to get. Thanks for your help.
1) https://i.stack.imgur.com/uwfZ5.png
2) https://i.stack.imgur.com/6nUJ2.png
my code
title: "Bundesliga - raport"
author: "aa aak"
date: "3 stycznia 2018"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE)
library(vcd)
```
## Bundesliga
a
```{r echo=FALSE}
head(Bundesliga)
```
Use the width option. This works on your example:
```{r echo=FALSE}
options(width = 100)
head(Bundesliga)
```

How to use LaTeX Code in R Chunk in R-Markdown?

I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.
For example
---
title: "test"
output: pdf_document
---
```{r, results='asis'}
for (i in 1:10) {
cat("\\section{Part:", i, "}")
summary(X)
$\alpha = `r X[1,i]`$
}
```
pretty much does the trick, but here there are still two problems:
the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible
Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?
I am very thankful for every kind of advice
You can do what you are after inline without relying as much on code blocks.
As a minimal example.
---
title: "test"
output: pdf_document
---
```{r sect1_prep, include=FALSE}
i <- 1
```
\section{`r paste0("Part: ", i)`}
```{r sect1_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
```{r sect2_prep, include=FALSE}
i <- i + 1
```
\section{`r paste0("Part: ", i)`}
```{r sect2_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
Produces...
If you really want to have a section factory, you could consider pander.
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
empty <- lapply(1:10, function(x) {
pandoc.header(paste0("Part: ", x), level = 2)
pander(summary(mtcars[, x]))
pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))
})
```
which produces...
remove summary table format example
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
content <- lapply(1:10, function(x) {
head <- pandoc.header.return(paste0("Part: ", x), level = 2)
body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))
return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))
})
writeLines(unlist(content), sep = "\n\n")
```

Resources