R Markdown pdf, page break in for loop without asis - r

I want to generate an rMarkdown pdf that for each of several variables has a summary table followed by a graph, and to put the table and graph for each variable on its own page.  If I use asis then the table formatting is lost.  If I omit asis, the way I insert the page break has no effect.  Since this is only for data exploration, I’m too lazy to do any post-processing ;-).  Is there a simple way to have my cake and eat it too?
---
output: pdf_document
---
some markdown text
```{r UglyTable, results = 'asis'}
for (n.var in 1:2) {
cat("\n\\pagebreak\n")
print(summary(iris[ , n.var]))
hist(iris[ , n.var])
}
```
more text
```{r NoPageBreaks}
for (n.var in 1:2) {
cat("\n\\pagebreak\n")
print(summary(iris[ , n.var]))
hist(iris[ , n.var])
}
```
 
These questions describe the use of pagebreaks with asis:  In Markdown PDF, how to add page break after each iteration of for loop?, rmarkdown: page break within a chunk?

Related

Using Markdown formatting in table using kable in quarto

Using quarto's HMTL-output functionalities, I am trying to produce a kable from a data.frame that contains some Markdown-style formatting that should show up in the final document. In the actual use case, I have a number of documents already formatted this way and I would like re-use these commands for correctly rendering the output.
Here's my example.qmd:
---
title: "example"
format:
html
---
```{r setup}
library(kableExtra)
```
```{r}
#| echo: false
data.frame(Function = "`read_delim()`",
Formula = "$\\leftarrow$",
Break = "this continues on a<br>new line",
Link = "[Google](www.google.com)") |>
kbl(format = "html")
```
After running the chunk, the preview in RStudio does display the arrow and line break correctly, but ` ` and the link fail to have an effect:
When rendering the qmd to HTML, the result looks like this, i.e. ignores the formatting:
What am I missing? Is there a way to include such formatting commands into a kable when rendering a quarto document to HTML?
When creating a table in Quarto, you can't mix Markdown with HTML - the Markdown syntax won't be processed within the HTML table.
This R code would work
data.frame(Function = "`read_delim()`",
Formula = "$\\leftarrow$",
Break = "this continues on a<br>new line",
Link = "[Google](www.google.com)") |>
kbl(format = "markdown")
So if you can, output only Markdown table which knitr::kable() should do by default.
If you need to output a HTML table (e.g for specific HTML features), you need to use a framework that will render the markdown for you while creating the HTML table.
gt with fmt_markdown() and md()
flextable with ftextra and colformat_md() or as_paragraph_md
This is possible that this limitation of note being able to include raw Markdown inside HTML table will be improve in the future (https://github.com/quarto-dev/quarto-cli/discussions/957#discussioncomment-2807907)

Rmarkdown Not Producing Table Within For In Loop

I'm trying to produce an automated report using Rmarkdown. In this report I have sections with tables. The sections are produced using the following Rmarkdown. However, it refuses to produce any tables(tried using kable and pander) when I hit knit. Knit will just produce the headings, without any tables. When I use the immediate mode, I get the appropriate markdown. So what might I be doing wrong.
```{r, results='asis'}
for(p in names(presentations)) {
deats <- presentations[p][[1]]
cat('#', p, '\n')
pander(deats)
str(deats)
cat('\n')
}
```
If using pander, disable the auto asis results:
```{r, results='asis'}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
for(p in names(mtcars)) {
cat('#', p, '\n')
pander(table(mtcars[, p]))
}
```
For more details, see the related Using pander with knitr vignette
When knitr::kable() or pander::pander() is not top-level R expression, you have to explicitly print it. You may see this post for more background information.

R Markdown makes custom plot disappear if I set echo=FALSE

I created a custom function which sets mfrow to nxn and creates n^2 scatter plots, with multiple data sets on each plot, based on an input list of data frames. The signature of my plotting function looks like this:
plot.return.list<-function(df.list,num.plot,title)
Where df.list is my list of data frames, num.plot is the total number of plots to generate (used to set mfrow) and title is the overall plot title (the function generates titles for each individual sub-graph).
This creats plots fine when I run the function from the console. However, I'm trying to get this figure into a markdown document using RStudio, like so:
```{r, fig.height=6,fig.width=6}
plot.return.list(f.1.list,4,bquote(atop("Numerical Approximations vs Exact Soltuions for "
,dot(x)==-1*x*(t))))
```
Since I haven't set the echo option in my {r} statement, this prints both the plotting code as well as the plot itself. However, if my first line instead reads:
{r, fig.height=6,fig.width=6,echo=FALSE}
Then both the code AND the plot disappear from the final document.
How do I make the plot appear WITHOUT the code? According to the example RStudio gives, setting echo=FALSE should make the plot appear without the code, but that isn't the behavior I'm observing.
EDIT: I seem to have tracked my problem down to kable. Whether or not I'm making a custom plot-helper function, any call to kable kills my plot. This can be reproduced in a markdown:
---
title: "repro"
author: "Frank Moore-Clingenpeel"
date: "October 9, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
options(default=TRUE)
repro.df<-data.frame((0.1*1:10)%*%t(1:10))
```
```{r, echo=FALSE}
kable(repro.df)
```
```{r, fig.height=6,fig.width=6,echo=FALSE}
plot(repro.df[,1],repro.df[,2])
```
In this code, the plot won't plot because I have echo set to false; removing the flag makes the plot visible
Also note that in my repro code, kable produces a table with a bunch of garbage in the last line--I don't know why, but this isn't true for my full original code, and I don't think it's related to my problem.
Thanks for the reproducible example. From this I can see that the problem is you don't have a newline between your table chunk and your plot chunk.
If you were to knit this and examine the MD file produced by knit (or set html_document as your output format and have keep_md: true to look at it), you would see that the table code and plot code are not separated by any newline. Pandoc needs this to delimit the end of the table. Without it, it thinks your ![](path/to/image.png) is part of the table and hence puts it as a "junk line" in the table rather than an image on its own.
Just add a newline between the two chunks and you will be fine. (Tables need to be surrounded with blank lines).
(I know you are compiling to LaTeX so it may confuse you why I am talking about markdown. In case it does, when you do Rmd -> PDF, Rmarkdown uses knit to go from RMD to MD, and then pandoc to go from MD to tex. This is why you still need to make sure your markdown looks OK).

How to integrate \newpage with table printing in Rmarkdown?

Do you know if in R markdown you can use go to the new page without distorting print(df) ie. data.frame's printing? For pdf generation the simple example is:
---
output: pdf_document
---
```{r, results='asis', echo=F, fig.width=8, fig.height=5}
for (year in 1:10) {
plot(1:year)
df<-data.frame(rep("costam", year),1:year)
cat("\n\n")
print(df)
cat("\\newpage")
}
```
Here, due to results='asis' the cat() command goes to new page; however, the data frame's are printed as strings.
It is helpful if you want to print chart together with its summary for a long... long... list of charts then can do it in a neat standardize way.

Format text inside R code chunk

I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.

Resources