How to evaluate all chunks in Rmarkdown - r

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)
```

Related

kableExtra stops evaluating latex code in table

I have an R Markdown table with this \rule{1cm}{0.4pt} LaTeX command in each cell of one column. The table formats just fine with kable if I do not include the kableExtra package. If I do include kabelExtra, the LaTeX command is no longer interpreted. The results are shown below, without and with kableExtra. No other change was made. The top example is my desired result.
I inspected the .tex output. kableExtra seems to format the LaTeX command as literal text: \textbackslash{}rule\{1cm\}\{0.4pt\} instead of the command shown above.
I want to use kableExtra for other features like setting column widths but I need it to interpret the LaTeX commands. I did not find anything in the manual or vignettes that seemed to address included LateX commands. Am I missing something?
Edit
I tried adding format = "latex" to the kable call when using kableExtra but undesired result remained.
MWE
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
#library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE)
```
Results
When using kableExtra you should add the argument escape = FALSE to your kable() call. The escape argument let you use LaTeX commands in table.
The following works:
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE,
escape = FALSE)
```

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

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)
```

Referencing a table in R markdown with knitr

It's possible to reference a figure in knitr like that:
```{r myfig}
plot(1,1)
```
Figure \ref{fig:myfig} shows ...
The same is not possible for tables, e.g.
```{r my_table, results='markup', fig.cap='capture'}
tab <- read.table('my_table.txt', sep = '\t')
kable(tab,
format='pandoc',
digits = 3,
caption =
"Description")
```
Table \ref{table:my_table} shows ...
doesn't work! Is it possible to make this work without digging into latex? If no, what would I have to do to make it work?
With format='pandoc' you need to enter the \label command in the caption.
With format='latex' the reference is automatically created as tab:chunk_label. For example,
---
output:
pdf_document
tables: true
---
```{r results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='pandoc',
digits = 3,
caption = "Pandoc table\\label{tab:pandoc_table}"
)
```
```{r latex_table, results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='latex',
digits = 3,
caption = "LaTeX table",
booktabs = TRUE
)
```
Table \ref{tab:pandoc_table} was done using Pandoc,
while Table \ref{tab:latex_table} used \LaTeX.
Replace table with tab \#ref(tab:my_table)

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.

Align xtable caption left in knitr

I have read a bunch of different posts on justifying xtable tables left but I cannot find details/work out how to make the caption justify left as well. Below is a reproducible example which justifies the table left but leaves the caption centred.
\documentclass{article}
\begin{document}
<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"), include.colnames=TRUE, size = "small", comment=FALSE, latex.environments="flushleft")
#
\end{document}
I have found out how to do this. Simply import the LaTex Caption package and use the caption setup argument:
\captionsetup{justification = raggedright, singlelinecheck = false}
This will justify the caption to the left. The caption can be returned to its default centred position for additional tables or figures by repeating the function with the following modification before additional tables/figures.
\captionsetup{justification = centering, singlelinecheck = false}
The answered solution is:
\documentclass{article}
\usepackage{caption}
\begin{document}
\captionsetup{justification = raggedright, singlelinecheck = false}
<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"),include.colnames=TRUE, size = "small", comment=FALSE, latex.environments="flushleft")
#
\end{document}
Which returns:
This operation is critical for anyone wishing to produce Markdown files in APA format since table captions are typically left-justified.
I'm going to clarify Robin's answer a little bit because, because totally new to the Markdown/Latex interface, it took me some time to figure out.
Upload the "caption" package (documentation available here) by including the
\usepackage{caption}
command in YAML (header) part of the document, preceded by
header-includes:
So an an entire YAML section at the header of the document might look like this:
---
title: "Supplementary Materials"
author: ""
date: "3/30/2018"
output:
pdf_document: default
editor_options:
chunk_output_type: inline
header-includes:
- \usepackage{caption}
---
Then, at any point in the document, before a code chunk (in its own white space), you can insert the code:
\captionsetup{justification = raggedright, singlelinecheck = false}
To change the settings back again, you can re-insert this code at any point in white space of the Markdown file (not in a code chunk!)
E.g.
\captionsetup{justification = centering, singlelinecheck = false}
If you don't mind using an alternative package (my own):
library(huxtable)
ht <- as_huxtable(df)
caption_pos(ht) <- "bottomleft"
print_latex(ht) # or just do `ht` if within a knitr or Rmd document

Resources