adding numbers to code blocks in RMD output - r-markdown

I am trying to add line numbers to code blocks, but it's not working. I'm using the code attr.source='.numberLines' with Pandoc 2.11.4. but the output files omit the code numbers.
I've tried the options referenced in this question and also the documentation from bookdown, but the attr.source='.numberLines' is being ignored and it doesn't show up as an autofill option, like say echo= would.
What I want is something that looks like this (just the number part)
Thanks! I've tried this in two different applications of R studio, and it's not working in either.
An example of the code I'm using:
---
title: "example"
author: "plover"
date: '2022-12-29. Version: `r Sys.Date()`'
output:
html_document:
code_folding: show
highlight: tango
number_sections: false
df_print: kable
theme: flatly
toc: yes
toc_float: yes
toc_depth: '3'
word_document:
toc: no
pdf_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Don't evaluate this code
```{r abc, eval = FALSE }
a <-1+1
b <-2+1
c = a + b
```
Don't evaluate this code, but show me the lines
```{r def, eval = FALSE, attr.source = '.numberLines' }
d <-3+1
e <-4+2
f = d + e
```
Evaluate this code, and show me the lines
```{r ghi, attr.source = '.numberLines' }
g <-3+1
h <-4+2
i = g + h
```

Try this. (Actually did nothing but comment out the yaml option code_folding: show)
---
title: "example"
author: "plover"
date: '2022-12-29. Version: `r Sys.Date()`'
output:
pdf_document:
toc: yes
word_document:
toc: no
html_document:
# code_folding: show
highlight: tango
number_sections: false
df_print: kable
theme: flatly
toc: yes
toc_float: yes
toc_depth: '3'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Don't evaluate this code
```{r abc, eval = FALSE }
a <-1+1
b <-2+1
c = a + b
```
Don't evaluate this code, but show me the lines
```{r def, eval = FALSE, attr.source=".numberLines"}
d <-3+1
e <-4+2
f = d + e
```
Evaluate this code, and show me the lines
```{r ghi, eval=FALSE, attr.source=".numberLines"}
g <-3+1
h <-4+2
i = g + h
```

Related

Flextable label not created in rmarkdown

I am using flextable to produce tables for a pdf document rendered with rmarkdwown. I want to cross-reference the tables, but they do not produce the label needed for the cross reference to work.
My Minimum Reproducible Example
What follows is the content of the file test.Rmd:
---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
pdf_document:
fig_caption: yes
includes:
in_header: header.tex
number_sections: yes
toc: yes
toc_depth: 4
latex_engine: xelatex
keep_tex: true
---
```{r, include = FALSE}
library(flextable)
library(bookdown)
opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```
```{r, tab.id = "anyTable", tab.cap = "Invented data", tab.lp = "tab:"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```
```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```
# Standard rmarkdown crossreference
Trying anyTable: \ref{tab:anyTable}.
Trying secondTable: \ref{tab:secondTable}.
# Bookdown crossreference
Trying anyTable: \#ref(tab:anyTable).
Trying secondTable: \#ref(tab:secondTable).
Contents of header.tex:
\usepackage{caption}
\renewcommand{\contentsname}{Contenidos}
\captionsetup[table]{name=Tabla}
\captionsetup[figure]{name=Figura}
%\usepackage{float} #use the 'float' package
%\floatplacement{figure}{H}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{xcolor}
\usepackage{multicol}
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}
When I do rmarkdown::render("test.Rmd", output_file = "test.pdf") the file is rendered in pdf, but the following warning comes out:
Output created: test.pdf
Warning message:
LaTeX Warning: Reference `tab:anyTable' on page 1 undefined on input line 198.
LaTeX Warning: Reference `tab:secondTable' on page 1 undefined on input line 20
0.
LaTeX Warning: There were undefined references.
If I check the .tex file, I can see that the captions are there, but they do not have the labels. The relevant lines of the intermediate test.tex file:
lines 106 to 109
\begin{longtable}[c]{|p{0.75in}|p{0.75in}}
\caption{Invented data
}\\
lines 153 to 156
\begin{longtable}[c]{|p{0.75in}|p{0.75in}}
\caption{This is secondTable
}\\
I expected that the caption line in the tex file was something like \caption{This is secondTable}\label{tab:secondTable}\\
What I've tried
Changing latex engines (lualatex, pdflatex, xelatex).
Editing the tex file (adding the label after the caption), but it fails to convert to dvi with multiple errors (mostly "undefined control sequence")
What am I doing wrong?
How can I cross-reference the tables produced by flextable?
Alternatively, I am open to other packages you may suggest. As some of the headers in my real data are somewhat complex (multi-span headers and the like), I would like to steer away from kable and kableExtra if at all possible.
You need to use a format from bookdown to get cross references, see https://bookdown.org/yihui/rmarkdown-cookbook/cross-ref.html
---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
bookdown::pdf_document2:
fig_caption: yes
number_sections: yes
toc: yes
toc_depth: 4
latex_engine: xelatex
keep_tex: true
---
```{r, include = FALSE}
library(flextable)
library(knitr)
library(bookdown)
opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```
```{r, tab.id = "anyTable", tab.cap = "Invented data"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```
```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```
# Bookdown crossreference
Trying anyTable: \#ref(tab:anyTable).
Trying secondTable: \#ref(tab:secondTable).

How to reduce space between title and content in pdf_output of Rmarkdown

I am using Rmarkdown to output pdf file. Here is the code:
---
title: |
| This is title
|
| \vspace{-5truemm}Supplementary Material\vspace{-5truemm}
author: 'xxx^[Correspondence to: xxx. Email: xxx]'
geometry: margin=0.3in
fontfamily: mathpazo
fontsize: 11pt
documentclass: article
urlcolor: blue
output:
pdf_document:
toc: true
toc_depth: 4
number_sections: yes
subparagraph: yes
header-includes: |
\usepackage{titlesec}
\titlespacing{\title}{0pt}{\parskip}{-\parskip}
---
\vspace{-5truemm}
# Introduction
This is introduction...
# Installation
This is installation...
## test1
### subtest1
And I want to know how to reduce space between the title (Supplementary Material) and content (not the body because I set toc as true).
Many thanks advanced!
As described in TeXSO, you can use the following package:
\usepackage{tocloft}
\setlength{\cftbeforetoctitleskip}{-\baselineskip}
So, the complete example would be like this.
---
title: |
| This is title
|
| \vspace{-5truemm}Supplementary Material\vspace{-5truemm}
author: 'xxx^[Correspondence to: xxx. Email: xxx]'
geometry: margin=0.3in
fontfamily: mathpazo
fontsize: 11pt
documentclass: article
urlcolor: blue
output:
pdf_document:
toc: true
toc_depth: 4
number_sections: yes
subparagraph: yes
header-includes: |
\usepackage{titlesec}
\titlespacing{\title}{0pt}{\parskip}{-\parskip}
\usepackage{tocloft}
\setlength{\cftbeforetoctitleskip}{-\baselineskip}
---
<!--
The following \vspace{} changes the spacing
between the first section ("Introduction" here)
and the last line of the title ("Supplementary Material")
-->
\vspace{-5truemm}
# Introduction
This is introduction...
# Installation
This is installation...
## test1
### subtest1
Note that the \vspace{} before the # Introduction changes the spacing
between the first section (Introduction here)
and the last line of the title (Supplementary Material).
Thus, the \vspace{} has nothing to do with
the space between the title and TOC.

Setting citation_package option under pdf_document in YAML Header and using rmarkdown::pdf_document function

The help file of the pdf_document function of the Rmarkdown CRAN package says that the function is defined with the following options:
pdf_document(toc = FALSE, toc_depth = 2, number_sections = FALSE,
fig_width = 6.5, fig_height = 4.5, fig_crop = TRUE,
fig_caption = TRUE, dev = "pdf", df_print = "default",
highlight = "default", template = "default", keep_tex = FALSE,
latex_engine = "pdflatex", citation_package = c("none", "natbib",
"biblatex"), includes = NULL, md_extensions = NULL,
pandoc_args = NULL, extra_dependencies = NULL)
I am under the impression that I could add any of these arguments as options under pdf_document in the output section of the YAML header in my Rmarkdown document. Is this correct? The document managed to compile when I used the following options/arguments of pdf_document: toc, number_sections, fig_caption, df_print, and keep_tex. However, when I add citation_package to the list, I get an error in compiling. For instance, consider the following template Rmarkdown document.
---
title: "Untitled"
author: "Unknown"
date: "4/18/2019"
output:
pdf_document:
# toc: true
number_sections: true
fig_caption: true
df_print: kable
keep_tex: true
citation_package: biblatex
bibliography: sample_bib.bib
csl: /Users/Shared/Zotero/styles/multidisciplinary-digital-publishing-institute.csl
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
I love R [#rcoreteamLanguageEnvironmentStatistical2018].
The sample_bib.bib mentioned is the bib file that looks like
#software{rcoreteamLanguageEnvironmentStatistical2018,
location = {{Vienna, Austria}},
title = {R: {{A Language}} and {{Environment}} for {{Statistical Computing}}},
url = {https://www.R-project.org/},
version = {3.5.1},
organization = {{R Foundation for Statistical Computing}},
date = {2018},
author = {{R Core Team}}
}
However, I was unable to knit this Rmarkdown document. I got the following error.
/usr/local/bin/pandoc +RTS -K512m -RTS rmarkdown_pdf_document.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output rmarkdown_pdf_document.tex --template /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/latex/default-1.17.0.2.tex --number-sections --highlight-style tango --pdf-engine pdflatex --biblatex --variable graphics=yes --variable 'geometry:margin=1in' --variable 'compact-title:yes'
output file: rmarkdown_pdf_document.knit.md
INFO - This is Biber 2.7
INFO - Logfile is 'rmarkdown_pdf_document.blg'
INFO - Reading 'rmarkdown_pdf_document.bcf'
INFO - Found 1 citekeys in bib section 0
INFO - Processing section 0
INFO - Looking for bibtex format file 'sample\_bib.bib' for section 0
ERROR - Cannot find 'sample\_bib.bib'!
INFO - ERRORS: 1
Error: Failed to build the bibliography via biber
Execution halted
Warning message:
LaTeX Warning: Citation 'rcoreteamLanguageEnvironmentStatistical2018' on page 1
undefined on input line 137.
LaTeX Warning: Empty bibliography on input line 169.
Package rerunfilecheck Warning: File `rmarkdown_pdf_document.out' has changed.
(rerunfilecheck) Rerun to get outlines right
(rerunfilecheck) or use package `bookmark'.
LaTeX Warning: There were undefined references.
LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.
Package biblatex Warning: Please (re)run Biber on the file:
(biblatex) rmarkdown_pdf_document
(biblatex) and rerun LaTeX afterwards.
Luckily, this problem is easily fixed by moving the "citation_package" from an option under pdf_document to a separate line in the YAML header. Or:
---
title: "Untitled"
author: "Unknown"
date: "4/18/2019"
output:
pdf_document:
# toc: true
number_sections: true
fig_caption: true
df_print: kable
keep_tex: true
citation_package: biblatex
bibliography: sample_bib.bib
csl: /Users/Shared/Zotero/styles/multidisciplinary-digital-publishing-institute.csl
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
I love R [#rcoreteamLanguageEnvironmentStatistical2018].
Upon knitting this adjusted Rmarkdown document, the result is a pdf_document.
So my question is: Was I right that you could add any of the arguments found in the pdf_document help file on CRAN as options under "pdf_document" in the YAML header in a Rmarkdown file? Or, upon using this particular citation_package argument/option, could this be a possible bug in the rmarkdown::pdf_document() function?
ALSO POSTED ON RMARKDOWN's GITHUB; see for additional comments.

Running code chunk in R-markdown using exam document class

I would like to run a code chunk under a question level in the exam document class, but I keep receiving errors. I am assuming this is because it believes the output from the R-code is Latex code.
---
output: pdf_document
documentclass: exam
header-includes: \usepackage{float}
---
\begin{questions}
\question Answer question...
```{r}
iris%>%
group_by(Species)%>%
summarize(Total=n())
```
\end{questions}
Sometimes \begin{"some environment") ... \end{"some environment") doesn't play well with R chuncks. One work around is to define a new environment.
For example, I defined a file preamble.tex with the following information:
preamble.tex
\usepackage{float}
\newcommand{\bQ}{\begin{questions}}
\newcommand{\eQ}{\end{questions}}
Then, I ran the following.
exam.Rmd
---
documentclass: exam
geometry: margin=.5in
output:
pdf_document:
highlight: haddock
includes:
in_header: preamble.tex
before_body: doc-prefix.tex
after_body: doc-suffix.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\bQ
## Including Plots
\question You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
```{r cars}
summary(cars)
```
\question We can keep the pound signs.
\eQ
Here is the resulting output.
Output
I managed to get something working. It needs some libraries and uses knitr to create the output.
---
output:
pdf_document:
keep_tex: true
documentclass: exam
header-includes: \usepackage{float}
---
```{r setup, include=TRUE,echo=FALSE,message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(knitr)
```
\begin{questions}
\question Answer question...
```{r, echo=F, comment=NA}
summary = iris %>% group_by(Species) %>% summarize(Total=n())
kable(summary, format='latex')
```
\end{questions}
The problem seems to be the inclusion of # in the output from R for processing by Latex. I avoid this by using kable.

R markdown hangs, but all code chunks work

R markdown gets stuck on chunk 1, which is repeated below:
---
title: "RMark1"
author: "df"
date: "11/19/2017"
output:
html_document:
toc: true
---
```{r setup}
library(dplyr)
library(knitr)
library(rmarkdown)
library(ggplot2)
library(plotly)
library(readr)
knitr::opts_chunk$set(echo = TRUE)
print("loaded libraries")
```
what am I missing here?