I am combining several .Rmd-files into one large document using bookdown. The individual files all contain footnotes, starting with ^[1]. This obviously leads to duplicate footnotes in the final document, with bookdown unable to assert which reference belongs to which footnote.
As a consequence, I am wondering whether there is a way to dynamically generate footnotes when the document is rendered, but I could not find anything related to that in the bookdown docs.
I have this working solution using a custom function:
---
title: "Untitled"
output:
html_document:
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
footnote.nr <- 0
footnote.counter <- function(){
footnote.nr <- footnote.nr + 1
.GlobalEnv$footnote.nr <- footnote.nr
return(footnote.nr)
}
```
Lorem ipsum.[^`r footnote.counter()`]
[^`r footnote.nr`]: Test
Lorem ipsum.[^`r footnote.counter()`]
[^`r footnote.nr`]: Test2
However, this would result in me having to retrofit the entire document which would be just as much manual labor as starting footnote numbering completely anew (though it is probably less error prone). Are there any other solutions? I would also be okay with footnotes being rendered for each individual chapter, meaning that the first footnote in each chapter starts with a 1.
In my humble opinion, #jtbayly's answer is only partially correct as using Rstudio's visual editing mode can indeed prompt it to make automatic changes to your text by adding a unique identifier before the citation (ex: [^love1]).
However, that did not initially work for me, and I had to add, for each child document the following option in the yaml header :
editor_options:
markdown:
references:
prefix: "[insert the unique identifier you want for this child document]"
This should then work, and would allow you to compile multiple .Rmd files into a single large document without RMarkdown/Pandoc messing with the citations. However, don't forget to go back to "Source" mode and "Visual" mode once after editing the yaml header for the editor to make the change.
Another option is to use Rstudio to edit your files, and turn on visual editing. If you do, it will make some automatic changes to your text, including giving your footnotes unique names.
Related
I am trying to write my master's thesis in RMarkdown.
I first tried to fix an issue with the position of my figures in the pdf document, and used this method : https://stackoverflow.com/a/33801326.
So my YAML header looked like this :
title: "example"
author: "me"
output:
rmarkdown::pdf_document:
fig_caption: yes
includes:
in_header: preamble-latex.tex
Then, I wanted my figures numbered and easily cross-referenced. I tried changing the output to bookdown::pdf_document2: since the method I was taught (that is ![caption\label{mylabel}] and \autoref{mylabel} ) did not work at all and ended up with this :
---
title: "example"
author: "me"
output:
bookdown::pdf_document2:
fig_caption: yes
includes:
in_header: preamble-latex.tex
---
```{r label, echo=FALSE, fig.cap="caption", out.width='75%', out.height='75%'}
knitr::include_graphics("../../images/my_image.png")
\```
and tried to cross-reference like this : #ref(fig:label)
The image does appear in the right place, at the right size and with my caption. But it is not numbered (there is no "Figure 1" mention before my caption) and the reference appears almost exactly as is in the knitted document, only without the backslash (so #ref(fig:label)). No matter where I look or what I do, I cannot seem to change that...
Could it be that bookdown's automatic numbering does not work because of the changes I made in the YAML header to keep my images in the right place? What can I do to fix this issue?
Problem has been solved by
giving up on using bookdown and coming back to the recommended output (that is ::rmarkdown:pdf_document: )
updating all R and tinytex packages
adding a line in the LaTex file :
/usepackage{float}
to fix an newly appeared error (unknown float option h)
The figures were then held in the right spot and numbered (although they weren't numbered before...)
using \autoref{fig:label} instead of \#ref(fig:label) for the cross-reference, in conjunction with include_graphics()
I am producing a Tutorial Workbook for my class using bookdown. I have a large class (500+), and so have a couple of other people helping me with the course.
So I would like to produce the answers for these tutorial questions.
I can produce a whole new document... but then it would be tricky to (automatically) cross-reference the exercise numbers.
So I wondered: Is there a way to password-protect a single page, or a single chapter, in bookdown? (Thinking HTML here; in PDF I can just not include that page/chapter.)
Is this possible? If so how? If not... any other ideas...?
P.
This solution does not use a password, but since you say that for PDF you can simply distribute a version that does not include the material in question, perhaps the following simple approach might help
Inspired by this question on how to conditionally input material as well as the option to use parameters in Rmarkdown, consider two Rmarkdown files:
main.Rmd, which contains what you want to show everyone.
protected.Rmd, which should only be shown to some people.
These files look as follows:
main.Rmd:
---
output: html_document
params:
include:
label: "Include extra material?"
value: ""
input: select
choices: [True, False]
---
```{r, include=FALSE}
print(params)
show_all <- as.logical(params$include)
```
```{r conditional_print, child="protected.Rmd", eval = show_all}
```
protected.Rmd:
Hello World!
Assuming you are in RStudio, if you choose "Knit with parameters" on main.Rmd, you will be asked to select either TRUE or FALSE from an interactive dropdown. If and only if you choose TRUE, the output will include "Hello World". More generally, code blocks with eval = show_all will only be displayed when selecting to include extra material. Therefore, you can of course have multiple sections (each contained in a separate .Rmd file) that are only conditionally included.
In this way, you could knit the same document twice: once with questions only, and once with questions and answers both. Since this is the same for both pdf and html, it also gives you a consistent workflow for both of these output types.
I teach an introductory statistics course using R Markdown in RStudio (Server). We have students knit to html_notebooks, and we often have them use inline code to report various elements of their statistical analyses. It'd be really helpful for grading purposes if we could have the result of inline code output in a different color -- that way we could easily see if they were indeed using inline code or if they copy-pasted a number from their output into raw text.
There's a couple of ideas for solutions posted here, but these won't super work in my case. These are introductory students who are generally kinda afraid of RStudio to begin with, so asking them to do anything complicated with text_spec or sprintf will likely cause mild riots. I really need something that won't change students' workflow at all.
I wonder if there's any way to configure things either on the backend in RStudio Server (maybe by messing with knitr?), or through some kind of <style> tag wizardry in the preamble, so that inline code will print its results in a different color.
Thanks!
EDIT: Arthur Berg below has provided something that's almost exactly what I need. Here's a MWE:
---
title: "test knit_hook"
output: html_document
---
```{r, setup, include="FALSE"}
knitr::knit_hooks$set(inline=function(x){paste0("<span style=\"color: #0000FF;\">",
x,"</span>")})
```
`r pi`
The only issue with this is that it doesn't work if I change to html_notebook in the YAML header and thus use the "Preview" button in the RStudio IDE. For external reasons, it's important for us to have the output type as html_notebook. Anyone know how we might modify this to get it to work with html_notebook?
A way to achieve this without changing the workflow too much is to create your own format (e.g. html_notebook2) that is derived from the original but modifies the inline hook of knitr.
To get started you can check out this document.
Basic steps include
Create a new R package
Within this project run usethis::use_rmarkdown_template(). This creates the folder structure for your new format.
Edit skeleton.rmd and template.yaml
Define your format in a R file which has the same name html_notebook2.R(kind of a convention).
The content of the html_notebook2.R file could be
#'#import knitr
set_hooks <- function() {
default_hooks <- knit_hooks$get()
list(
inline = function(x) {
paste0("<span style=\"color: #FF0000;\">", x,"</span>")
})
}
#' #importFrom rmarkdown output_format knitr_options pandoc_options html_notebook
#' #export
html_notebook2 = function() {
output_format(
knitr = knitr_options(knit_hooks = set_hooks()),
pandoc = pandoc_options(to = "html"),
clean_supporting = FALSE,
base_format = html_notebook()
)
}
In the first part we define a new inline hook which only changes the font color.
The second part is the definition of the new format.
After building and installing the package you can create a new rmarkdown document and use output: packagename::html_notebook2 as the output format. All inline code output will be colored red using my code. Here is an example:
---
title: "Inline"
output: cformat::html_notebook2
---
## R Markdown
`r pi`
I created such a package and you can find it on GitHub. Feel free to copy it and rename it (cformat is a pretty lame working title ;) ).
Notice though that your students could change the color manually using HTML/CSS anyways. A way around could be some kind of key generation using a certain rule (unknown to the students obviously). For each inline chunk a key is generated and embedded using
paste0("<span code=", key," style=\"color: #FF0000;\">", x,"</span>")
If a valid key is embedded, the output was generated using R and not simply copied.
For those looking for a fix to a simple R markdown document, adding this line changes the inline output to blue.
knitr::knit_hooks$set(inline=function(x){paste0("<span style=\"color: #0000FF;\">", x,"</span>")})
I'm writing a scientific manuscript in RMarkdown using the papaja package, which enables me to report my statistics beautifully. However, the journal now requires me to submit a Word document with number-letter referencing. Is it possible to change the referencing style to a number-letter style in Papaja?
I tried opening the LaTeX output from papaja, but it has the citations set out in the text in APA format (e.g. "Apthorp, Bolbecker, Bartolomeo, O'Donnell, \& Hetrick, 2018"), which is not useful to me.
Here's the code from the top of the manuscript:
bibliography : ["PD_sway-1.bib"]
floatsintext : no
figurelist : no
tablelist : no
footnotelist : no
linenumbers : yes
mask : no
draft : no
documentclass : "apa6"
classoption : "man"
output : papaja::apa6_pdf
It would be great if I could get a Word document with number-letter referencing that I could then edit, but a LaTeX file or PDF with the correct citation format would be fine too.
The references are already typed out in APA style in the LaTeX document because they are handled by pandoc-citeproc rather than LaTeX. This has the advantage that the automatic reference formatting also works when you output your document in Word format. To get a Word document all you need to do is change the output line in the YAML front matter:
output: papaja::apa6_docx
Note that the formatting of Word documents that pandoc supports is somewhat limited and you may have to fix some things manually. From the corresponding section in the papaja manual:
More over, rendered documents in DOCX format require some manual work before they fully comply with APA guidelines.
We, therefore, provide the following checklist of necessary changes:
Always,
add a header line with running head and page number
If necessary,
position author note at the bottom of page 1
move figures and tables to the end of the manuscript
add colon to level 3-headings
in figure captions,
add a colon following the figure numbers and italicize(e.g. "Figure 1. This is a caption.")
in tables,
add horizontal rules above the first and below the last row
add midrules
Changing the citation style works just as it does in any R Markdown document. The work-in-progress papaja manual has a section on this:
Other styles can be set in the YAML front matter by specifying a CSL, or Citations Style Language, file. You can use either one of the large number of existing CSL files, customize an existing CSL file, or create a new one entirely.
To change the citation style, download the CSL file and add the following to the YAML front matter:
csl: "path/to/mystyle.csl"
I'm not sure what style the journal requires but most likely a corresponding CSL file already exists.
I'd like for a chapter to appear before the table of contents (but after the title page) in the pdf_book output of Bookdown.
One way to do this is to add the chapter to a .tex file and and link it using before_body:. However, this means the chapter will not appear in gitbook (which I also need). I'd prefer not to keep both a .tex and .Rmd version of the same chapter.
An ideal solution would be if the chapter could be kept in a .Rmd file, and its contents extracted into the before_body for pdf_book. That way it's still available for gitbook. Though I'm not sure how I might do that, or indeed if it's possible?
Is there a solution? Or is it exceeding the limits of Bookdown's flexibility?
Any help would be greatly appreciated, thanks!
One can trigger ToC creation manually in the document, which gives more control over its placement. Of course, automatic table of contents creation should be disabled:
---
title: "MWE"
output:
bookdown::pdf_book:
toc: False
---
```{r child = 'file-you-want-to-include.Rmd'}
```
```{=latex}
% Trigger ToC creation in LaTeX
\tableofcontents
```
# Rest of your document starts here
The downside is that this only works with PDF output, not HTML.