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
```
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.
I'm using a chunk of bash code in my R Markdown document (.Rmd).
A minimal example looks like this:
```{bash}
MY_NAME='Fred'
echo $MY_NAME
```
When I knit this, I get no output, meaning, the variable is not recognized.
When I do the same in my Unix console, it outputs 'Fred'. Any hint as to why the variable doesn't seem to be stored?
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))"
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().