r markdown output to pdf: stop plot breaking up a code chunk - r

I am printing an r markdown file to pdf. I've tried various output specifications, but the plot keeps displaying in the middle of segments [1] and [2].
I want the all of the code to be displayed one chunk, and will call the plot later in the document.
```{r, include=TRUE, results='hide'}
# [1] There is code up here
# [plot interrupts the code chunk here] Scatter plot
plot1 = plot(df$var1, df$var)
# [2] More code below this point
```

Use the chunk option fig.show = 'hold' to display all the plots produced by a chunk at the end of the chunk. Here is an example .Rmd file and output.
---
title: Stop Plot Breakikng Up Code Chunk
output: pdf_document
---
The key is to use the chunk option `fig.show = 'hold'` so that all plots from
the chunk will will displayed at the end of the chunk.
```{r setup, include = FALSE, cache = FALSE}
library(knitr)
opts_chunk$set(fig.show = "hold")
```
We'll use the `mtcars` data set for the example.
```{r plot1, include = TRUE, results = "hide"}
mean(mtcars$wt)
mean(mtcars$mpg)
plot(mtcars$wt, mtcars$mpg)
var(mtcars$wt)
```
End of example.
EDIT:
Another solution, closer to what I think you are looking for, is to use ref.label to reuse code chunks.
---
title: Stop Plot Breaking Up Code Chunk
output: pdf_document
---
The key is to use the chunk option `fig.show = 'hold'` so that all plots from
the chunk will will displayed at the end of the chunk.
```{r setup, include = FALSE, cache = FALSE}
library(knitr)
opts_chunk$set(fig.show = "hold",
collapse = TRUE)
```
We will use the `mtcars` data set for the example.
```{r all_code}
```{r mean_code, ref.label = "means", echo = TRUE, results = "hide"}
```{r plot1_code, ref.label = "plot1", echo = TRUE, fig.show = "hide", fig.keep = "none"}
```{r var_code, ref.label = "var_wt", echo = TRUE, results = "hide"}
```
Description of a plot
```{r "plot1", echo = FALSE}
plot(mtcars$wt, mtcars$mpg)
```
More text.
Below here, chunks that are evaluated, but not shown.
```{r means, include = FALSE}
mean(mtcars$wt)
mean(mtcars$mpg)
```
```{r var_wt, include = FALSE}
var(mtcars$wt)
```
End of the example.

You can write 2 chunks :
## Title
Herebelow the code are not separated by plots :
```{r display_code_only, eval=FALSE}
plot(pressure)
plot(iris)
```
Herebelow the plot are not separated by code :
```{r display_plot_only, echo=FALSE}
plot(pressure)
plot(iris)
```

Related

knitr::include_graphics: safe way to read from the project directory?

I am trying to make a RMarkdown report using bookdown::html_document2 to create numbered Fig. 1, Fig. 2, ... across the whole document. Here, I am using both the R-generated and the external figures. I have found that using include_graphics() will help to generate a proper Fig. X numbers, also including in numbering the external figures.
To get the script to work, I am declaring the root.dir = rprojroot::find_rstudio_root_file('C:/myRproject')) while my external figures are located within C:/myRproject/inImg. But in this case, R cannot find my external images anymore? Why is this and how can I properly claim the paths for my R Markdown input, and for external figures? Thank you!
Example:
---
title: "My awesome title"
author: "me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
toc_depth: 3
knit: (function(input, ...) {
rmarkdown::render(
input,
output_dir = "../outReports",
output_file = file.path("../outReports", glue::glue('test_{Sys.Date()}'
)))
})
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, tidy = TRUE, tidy.opts = list(comment = FALSE), message = F, warning = F)
knitr::opts_chunk$set(fig.width=6, fig.height=3)
library(knitr)
library(png)
```
```{css, echo=FALSE}
p.caption {
font-size: 0.8em;
}
```
```{r setup-root}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))
```
```{r read-libs, eval = TRUE, echo=FALSE, include = FALSE, warning = FALSE, error = FALSE }
# rm(list=ls())
getwd()
#### Source paths and functions -----------------------------------------------
source('myPaths.R') # already this one I can't find within the directory?
# Read pictures as part of teh R chunks
library(knitr)
library(png)
# Read Input data -------------------------------------------------------------------
#getwd()
load(file = "outData/dat1.Rdata")
```
## Including Plots
You can also embed plots, for example:
```{r, out.width = "50%", fig.cap = 'Add fig from internet'}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```
```{r add-extern-plot2, fig.cap = 'my numbered caption'}
# All defaults
img1_path <- "C:/myRproject/inImg/my_extern_fig.png"
img1 <- readPNG(img1_path, native = TRUE, info = TRUE)
attr(img1, "info")
include_graphics(img1_path)
```

Rotate table pdf output from Markdown

I want to rotate table output by 90 degrees on pdf. I am using markdown to generate a report and kable to display the tables in a loop. If possible, I would like to continue using kable since there are lot of other things which are dependent on it that I haven't included in this MWE.
This is a simple example using iris dataset. I tried using landscape function from this post Rotate a table from R markdown in pdf
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
longtable = TRUE, row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```
But this only rotates the page number keeping the table as it is.
I am actually looking for a solution which provides me the output in this way -
To clarify, all the pages with table data in it (3 for this example) should be rotated whereas rest of them should remain as it is. Also, I need longtable = TRUE in kable since in my actual example I am printing lot of rows.
Use package rotating
I added a simple example for you.
---
title: "test"
header-includes: \usepackage[figuresright]{rotating}
#or \usepackage[figuresleft]{rotating}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include = FALSE}
library(flextable)
ft <- flextable(head(mtcars))
```
\begin{sidewaysfigure}
`r ft`
\end{sidewaysfigure}
```
Further you can modify it for your tasks ;)
I found another way using rotatebox.
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
\usepackage{graphicx}
\usepackage[figuresright]{rotating}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis', warning=FALSE, message=FALSE}
library(knitr)
library(kableExtra)
for (i in 1:3) {
cat('\\rotatebox{90}{')
print(kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
row.names = FALSE))
cat('}')
cat("\n\\newpage\n")
}
```

Create code snippets by a loop in rmardown

Similar to how to create a loop that includes both a code chunk and text with knitr in R i try to get text and a Code snippet created by a Loop.
Something along this:
---
title: Sample
output: html_document
params:
test_data: list("x <- 2", "x <- 4")
---
for(nr in 1:3){
cat(paste0("## Heading ", nr))
```{r, results='asis', eval = FALSE, echo = TRUE}
params$test_data[[nr]]
```
}
Expected Output would be:
What i tried:
I tried to follow: https://stackoverflow.com/a/36381976/8538074. But printing "```" did not work for me.
You can make use of knitr hooks. Take the following MRE:
---
title: "Untitled"
output: html_document
params:
test_data: c("x <- 2", "x <- 4")
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, results = 'asis', echo = F}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()
chunks <- eval(parse(text = params$test_data))
for(nr in seq_along(chunks)){
cat(paste0("## Heading ", nr, "\n"))
cat(hook(chunks[nr], options = opts))
}
```
We get the default source hook and also the default chunk options. Then we get the test data, which is supplied as a string. Therefore we parse and evaluate that string.
In the loop we simply call the source hook on each element of the test data. Here is the result:

How to evaluate all chunks in Rmarkdown

How do I evaluate all of the chunks in an Rmd document, without putting eval=TRUE at each chunk? The way I have it below, only the first chunk is evaluated.
```{r,eval=TRUE}
1+1
```
Some text
```
2+2
```
EDIT:
I'm trying to knit/compile to HTML.
```
require(knitr)
opts_chunk$set(eval = TRUE, tidy = TRUE, cache = FALSE, echo = FALSE, include = FALSE,
fig.path = 'figures/', dev = c("pdf"),
fig.width = 7, fig.height = 7)
```
some text
```
1+1
```
more text
```
2+2
```
eval=TRUE is the default behaviour for .Rmd chunks, so you shouldn't need to explicitly add it to your chunks' options.
However, you do need to include {r} after your opening fences in order for the chunk to be recognised as R code and evaluated accordingly. Chunks that do not open with ```{r} will not be run, hence the problem you're seeing.
A working example might be:
```{r}
1+1
```
Some text
```{r}
2+2
```
To insert a new, empty chunk with the appropriate fences and {r}, you can press Ctrl + Alt+i on Windows, or ⌘ + Option + i on Mac, or click this icon at the top right of the RStudio source pane (from memory, older versions of RStudio had an 'Insert' drop-down in that general area):
In your first chunk you can set knitr options globally.
opts_chunk$set(tidy = TRUE, cache = FALSE, echo = FALSE, include = FALSE,
fig.path = 'figures/', dev = c("pdf"),
fig.width = 7, fig.height = 7)
In any subsequent chunk, you can change these by the usual means but they only apply to that chunk.
EDIT. Here is a fuller example from K. Broman
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE)
```

Rmarkdown table pushed to two pages when it can fit in one

I'm trying to create separate Rmd files for different tables where each table gets rendered to separate pdfs. Because of some complex formatting issues, I'm using xtable to try and pull this off. I have some tables that I anticipate will fill up a full 8.5x11.0 page with 1 inch margins. But when I render them the first page of the pdf is blank and the second page has the entire, properly formatted table. I'm looking for help to get this to work right. Here's my minimal workable example...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE
)
```
This gets saved as test.Rd and I render using...
library(rmarkdown)
render("test.Rmd"
If I change the margin sizes, it seems to only affect the left and right margin. If I shrink the size of the font, it will fit on one page, but I'd like to keep the font size as is and get rid of the blank first page. Ideas? I'm a bit of a latex newbie so apologies for missing something obvious.
I think if you add the floating = FALSE argument, it should solve the problem. I think this is the LaTex equivalent of the !h here argument when you define the table. I also separated the library call from the other code (and used library instead of require), but that's stylistic and picky.
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r echo=FALSE, warning=FALSE, eval=TRUE, results='hide'}
library(xtable)
```
```{r eval=TRUE, echo=FALSE, results='asis'}
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
floating=FALSE
)
```
Thanks to the posting from ted-dallas, I was able to figure out that the table.placement option did what I want without having to turn off the floating...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
table.placement = "!ht"
)
```
This generates the output I was looking for.

Resources