How can I create a single output document with bookdown, e.g. using its bookdown::html_document2 format, and still have a Table of Contents somewhere in the output document?
For example, I check out the content from https://github.com/tidyverse/style, and run
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::html_document2')"
Then I get a _main.html as desired, with all the text from all chapters, but no TOC is present.
You can use the dots (...) argument of bookdown::html_document2 to pass toc = TRUE to rmarkdown::html_document:
Rscript -e "bookdown::render_book('index.Rmd', bookdown::html_document2(toc = TRUE))"
Related
For typical R scripts the shebang syntax can be used to run the code within. With a file file.R
#!/usr/bin/env Rscript
<some R code here>
Running ./file.R will execute the code.
But can somehow the same be done with R-markdown? So that with a file named file.Rmd:
#!/usr/bin/env <some command>
<some markdown>
<some R code here>
<some markdown again>
Running ./file.Rmd would produce file.md?
You can treat an Rmd file as an Rscript. For instance, assume that your Rmd file looks like this
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
You can then prepend the following code to that Rmd file
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
The trick here is q("no"). This line terminates the R session, and, thus, whatever written after it will be ignored. Such an effect also means high flexibility for coding because you can write almost any valid R code before that q("no"). The code above simply creates another temporary Rmd file with the same content as what is after q("no"). Then, we rmarkdown::render that temporary file and dump the output to the current directory.
The complete Rmd file looks like this
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Disclaimer: I do not know much about Linux, nor do I have a Linux machine with R installed available to test my answer. Let me know if this does not work properly. If this inspires someone to write a better answer, I'll happily delete this one.
Let me approach this backwards:
To knit a document, we need to call rmarkdown::render().
To run this command from a command line, we can use RScript -e "rmarkdown::render('document.Rmd')", see e.g. here.
Probably you do not want to hardcode the path to Rscript but use a shebang like #!/usr/bin/env Rscript instead.
The problem with this approach is that it does not allow to pass arguments to Rscript.
I therefore propose to use a "wrapper" in the shebang that is responsible for calling Rscript.
With the name of the RMD file as argument, the required R code becomes rmarkdown::render(commandArgs(trailingOnly=TRUE)[1]).
Step by step:
Create the wraper (in any directory that is in your $PATH) and make it executable:
touch KnitWrapper.sh
chmod +x KnitWrapper.sh
Write the following to KnitWrapper.sh:
#!/usr/bin/env bash
Rscript -e "rmarkdown::render(commandArgs(trailingOnly=TRUE)[1])" $1
Make sure Rscript is in your $PATH. If you update R, update your $PATH accordingly.
In your RMD file, add the shebang #!/usr/bin/env KnitWrapper.sh.
Make your RMD file executable and run it:
chmod +x yourDocument.Rmd
./yourDocument.Rmd
Unfortunately, the above is largely untested. Let me know if it does not work, so I can either fix or delete this answer.
Rmarkdown chunks by default display the input code block and the output block. The code block is highlighted by default and the output verbatim text is usually not. If I am running some code that generates more code, is it possible to show code highlighting in the output block?
For example, this chunk executes R code
```{r,echo=FALSE}
paste0("cp -R ",getwd(),"/* ./dir")
```
to generate valid shell code as the output.
"cp -R /home/user/work/* ./dir"
Can this output be code highlighted for shell script? The output code does not have to be evaluated.
Use the chunk option class.output and specify the language name, e.g.
```{r, class.output='sh', comment=''}
cat('ls -l "$HOME"') # sh for shell scripts
```
I'm using knitr to create a markdown file from Rmd and I have the following option set at the top of my .Rmd script to hide all results and plots:
```{r, echo=FALSE}
opts_chunk$set(results="hide", fig.show="hide")
```
When I hit the Knit HTML button in RStudio, this works - I get output without the results and figures. But if I run from the command line:
Rscript -e 'knitr::knit("myfile.Rmd")'
It appears the opts_chunk$set() line isn't read, and I get results and plots in my .md output. I've worked around the problem by specifying these options in the Rscript command:
Rscript -e 'library(knitr); opts_chunk$set(results="hide", fig.show="hide"); knit("myfile.Rmd")'
But I'd rather keep all the options read from the file I'm using rather than specified at the command line. How do I get the options read in the .Rmd file when kniting with Rscript at the command line?
Thanks.
I think you need to add
library("knitr")
to the chunk (you might want to set message=FALSE in the chunk options for that chunk).
The problem is that when you do
Rscript -e 'knitr::knit("myfile.Rmd")'
you're not actually attaching the knitr package, which means it isn't in the search path for functions, which means that R can't find the opts_chunk object.
Using knitr::opts_chunk might work too ...
as you suggested, so does Rscript -e 'library("knitr"); knit("myfile.Rmd")'
When you click the button in RStudio, RStudio automatically loads knitr in the environment in which it runs knit().
I'm using knitr to create a markdown file from Rmd and I have the following option set at the top of my .Rmd script to hide all results and plots:
```{r, echo=FALSE}
opts_chunk$set(results="hide", fig.show="hide")
```
When I hit the Knit HTML button in RStudio, this works - I get output without the results and figures. But if I run from the command line:
Rscript -e 'knitr::knit("myfile.Rmd")'
It appears the opts_chunk$set() line isn't read, and I get results and plots in my .md output. I've worked around the problem by specifying these options in the Rscript command:
Rscript -e 'library(knitr); opts_chunk$set(results="hide", fig.show="hide"); knit("myfile.Rmd")'
But I'd rather keep all the options read from the file I'm using rather than specified at the command line. How do I get the options read in the .Rmd file when kniting with Rscript at the command line?
Thanks.
I think you need to add
library("knitr")
to the chunk (you might want to set message=FALSE in the chunk options for that chunk).
The problem is that when you do
Rscript -e 'knitr::knit("myfile.Rmd")'
you're not actually attaching the knitr package, which means it isn't in the search path for functions, which means that R can't find the opts_chunk object.
Using knitr::opts_chunk might work too ...
as you suggested, so does Rscript -e 'library("knitr"); knit("myfile.Rmd")'
When you click the button in RStudio, RStudio automatically loads knitr in the environment in which it runs knit().
I am trying to use Pandoc to convert a .md file to PDF. In doing this, I would like to add a LaTeX template into it. Is there a way to do this? If so, what is the command for doing it in RStudio?
The command I am currently using is the following
```{r}
pandoc("foo.md", format="latex")
```
Thank you in advance.
One way to do it is to use the function system and run pandoc directly, adding a Latex header.
For example:
system("pandoc -f markdown -t latex -o foo.pdf -H template.tex -V papersize:\"a4paper\" -V geometry:\"top=2cm, bottom=3cm, left=2cm, right=2cm\" foo.md ")
-f inicates the origin language, though I mix MarkDown and Latex and it works fine.
-t is the result language, though it really compiles the created latex and what you get is a .pdf document
-o the name of the file you want to create
-H a header to add. There is where you can put your template
-V many variables that you can set. Here I set the paper size and margins
at the end you write the name of your MarkDown file
template.tex is a tex file with the header I want in the Latex document. I use it to add packages, headers and some other parameters. For example:
\usepackage{booktabs}
\usepackage[spanish, es-tabla]{babel}
\usepackage{colortbl}
\usepackage{float}
\usepackage{fancyhdr}
\usepackage[singlelinecheck=false]{caption}
\setlength{\headheight}{40pt}
\pagestyle{fancy}
\lhead{My Title}
\rhead{\includegraphics[height=50pt]{MyGraph.png}}