I am using knitr to parse an R Markdown document . Is there a way to conditionally display a block of text in R Markdown depending on a variable in the environment I pass into knitr?
For instance, something like:
`r if(show.text) {`
la la la
`r }`
Would print "la la la" in the resulting doc if show.text is true.
You need a complete R expression, so you cannot break it into multiple blocks like you show, but if the results of a block are a text string then it will be included as is (without quotes), so you should be able to do something like:
`r if(show.text){"la la la"}`
and it will include the text if and only if show.text is TRUE.
You can do this using the "eval" chunk option. See http://yihui.name/knitr/options/.
```{r setup, echo=FALSE}
show_text <- FALSE
````
```{r conditional_block, eval=show_text}
print("this will only print when show.text is TRUE")
```
I've been using YAML config files to parameterize my markdown reports which makes them more reusable.
```{r load_config}
library(yaml)
config <- yaml.load_file("config.yaml")
```
...
```{r conditional_print, eval=config$show_text}
print("la la la")
````
I find it easiest to do this by putting all of my text into a separate file and then include it from the main file with:
```{r conditional_print, child='text.Rmd', eval = show_text}
```
This has the advantage that you can still put inline R statements or other chunks into the child file, so that if you change your mind about what counts as optional text, you don't have to refactor your project.
Here's a tweak to Paul Boardman's approach that gives proper markup in the output.
```{r setup, echo=FALSE}
show_text <- FALSE
```
```{r conditional_block, echo=FALSE, results='asis', eval=show_text}
cat("## Hey look, a heading!
lorem ipsum dolor emet...")
```
Even better, if we invoke the python engine to generate our output, we can use triple quoting to easily handle text that contains single or double quotes without needing to do anything fancy:
```{python, conditional_block_py, echo=FALSE, results='asis', eval=show_cond_text}
print("""
## Still a heading
Block of text with 'single quotes' and "double quotes"
""")
```
The solutions above may be a little clunky for larger blocks of text and not great for certain situations. Let's say I want to create a worksheet for students with some questions and also use the same .Rmd file to generate a file with solutions. I used basic LaTeX flow control:
``` {r, include = F}
# this can be e.g., in a parent .Rmd and the below can be in child
solution <- TRUE
```
\newif\ifsol
\sol`r ifelse(solution, 'true', 'false')`
Then I can do:
What is $2 + 2$
\ifsol
4
\fi
This way you can also create alternative blocks of text using
\ifsol
Alternative 1
\else
Alternative 2
\fi
The accepted answer above works well for inline content.
For block content (one of several paragraphs of Markdown text), knitr contains a asis engine that allow to include Markdown content conditionnally depending if chunk option echo = FALSE or echo = TRUE
Example from the doc https://bookdown.org/yihui/rmarkdown-cookbook/eng-asis.html
```{r}
getRandomNumber <- function() {
sample(1:6, 1)
}
```
```{asis, echo = getRandomNumber() == 4}
According to https://xkcd.com/221/, we just generated
a **true** random number!
```
If you need to include more complexe content , like piece of a R Markdown document with e.g code block, then child document could be useful. See https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html
Another way to add markdown text conditionally is below. It uses the block "engine" which seems to run fine although I'm not sure how to make inline R evaluation working.
Note that I use the view_all switch defined in the YAML metadata to control whether or not the block is visible.
Also, note that both eval and include chunk options are needed.
The first prevents errors during regular Run All in RStudio.
The second prevents output with Knit.
---
title: "Conditional Output"
params:
view_all: false
output:
html_document: default
pdf_document: default
---
```{block eval=FALSE, include=params$view_all}
# Some simple markdown.
Some things work: $2 + 2^2 = 3\cdot2$
Other does not: 2 + 2 = `r 2+2`
```
I tried to define a function my.render(), which preprocesses the Rmd file, and depending on the commentout argument, either keeps the HTML commenting code (TRUE) in the Rmd file or removes them (FALSE). Then writes the preprocessed Rmd file into tmp.Rmd, and uses the usual render() function.
my.render <- function(input, commentout=FALSE, ...) {
if (commentout == FALSE) {
## Delete the HTML comment lines from code
txt <- readLines(input)
txt[grepl(" *<!-- *| *--> *", txt)] <- ""
write.table(txt, file="tmp.Rmd", sep="\n", quote=FALSE, row.names=FALSE, col.names=FALSE)
render("tmp.Rmd", output_file=sub("Rmd","html",input), ...)
} else {
render(input, output_file=sub("Rmd","html",input), ...)
}
}
It seemed to work. E.g.
<!--
This text with formulas $\alpha+\beta$ is visible, when commentout=FALSE.
-->
Related
Is there anyway to format code in the "code" format offered by many websites like Stackoverflow in R Markdown.
I want to be able to do something like the following:
Any model that takes the form income ~ education + parental_income
...
I want to emulate that greyed out text in R markdown for ease of readability when I eventually knit the document.
One can use backticks or indenting by 4 spaces to generate the equivalent of the HTML <code> </code> tag block. Here is an Rmd document illustrating this behavior.
---
title: "Sample Document"
author: "bigNumber"
date: "12/5/2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
here is some example code written in R Markdown. If we want to enter a code block we use the backtick, such as `inc ~ ed + occ`.
If we want a code block with multiple lines, indenting by 4 spaces also works
# first line of code
for(i in 1:100) {
# do something here
}
More text after the code block ends.
...and the output. Unfortunately I have to include an image to show that it renders correctly.
```
If you'd rather not
indent your code block by four spaces, you can use
triple back-ticks on separate lines.
```
https://bookdown.org/yihui/rmarkdown/markdown-syntax.html#block-level-elements
html could work if you want to have a string with gray color as a background
Changing chunk background color in RMarkdown
How do you get rmarkdown to include a code chunk as part of a list?
Example:
Something about some code - you could try this_fun
A more complicated way is to do
```{r, eval = FALSE}
a(
large(
nested(function)))
```
And that may suit your use case
Skip it all together
Originally I was using the vanilla ``` code chunk, but that gives up syntax highlighting, and inline gives up highlighting and newlines/indentation. If the code is used as above the list is broken, and the text following the chunk becomes embedded in a weird environment (something like the output formatting).
Anyone know if this can be done?
Are you looking for that?
(Save the following code as Rmd file)
---
title: "Untitled"
output: html_document
---
1. Something about some code - you could try this_fun.
1. A more complicated way is to do
```{r, eval = FALSE}
a <- function() { # whole chunk indented by 4!
return(2)
}
print(a())
```
And that may suit your use case
1. Skip it all together
It look like that:
One of the features I like very much in Sweave is the option to have \SweaveInput{} of separate Sweave files to have a more "modular" report and just be able to comment out parts of the report that I do not want to be generated with a single #\SweaveInput{part_x} rather than having to comment in or out entire blocks of code.
Recently I decided to move to R Markdown for multiple reasons being mainly practicality, the option of interactive (Shiny) integration in the report and the fact that I do not really need the extensive formatting options of LaTeX.
I found that technically pandoc is able to combine multiple Rmd files into one html output by just concatenating them but it would be nice if this behaviour could be called from a "master" Rmd file.
Any answer would be greatly appreciated even if it is just "go back to Sweave, it is not possible in Markdown".
I am using R 3.1.1 for Windows and Linux as well as Rstudio 0.98.1056 and Rstudio server 0.98.983.
Use something like this in the main document:
```{r child="CapsuleRInit.Rmd"}
```
```{r child="CapsuleTitle.Rmd", eval=TRUE}
```
```{r child="CapsuleBaseline.Rmd", eval=TRUE}
```
Use eval=FALSE to skip one child.
For RStudio users: you can define a main document for latex output, but this does not work for RMD documents, so you always have to switch to the main document for processing. Please support my feature request to RStudio; I tried already twice, but is seems to me that too few people use child docs to put it higher in the priority list.
I don't quite understand some of the terms in the answer above, but the solution relates to defining a custom knit: hook in the YAML header. For multipartite documents this allows you to, for example:
Have a 'main' or 'root' Rmarkdown file with an output: markdown_document YAML header
render all child documents from Rmd ⇒ md ahead of calling render, or not if this is time-limiting
combine multiple files (with the child code chunk option) into one (e.g. for chapters in a report)
write output: html_document (or other format) YAML headers for this compilation output on the fly, prepending to the markdown effectively writing a fresh Rmarkdown file
...then render this Rmarkdown to get the output, deleting intermediate files in the process if desired
The code for all of the above (dumped here) is described here, a post I wrote after working out the usage of custom knit: YAML header hooks recently (here).
The custom knit: function (i.e. the replacement to rmarkdown::render) in the above example is:
(function(inputFile, encoding) {
input.dir <- normalizePath(dirname(inputFile))
rmarkdown::render(input = inputFile, encoding = encoding, quiet=TRUE,
output_file = paste0(input.dir,'/Workbook-tmp.Rmd'))
sink("Workbook-compiled.Rmd")
cat(readLines(headerConn <- file("Workbook-header.yaml")), sep="\n")
close(headerConn)
cat(readLines(rmdConn <- file("Workbook-tmp.Rmd")), sep="\n")
close(rmdConn)
sink()
rmarkdown::render(input = paste0(input.dir,'/Workbook-compiled.Rmd'),
encoding = encoding, output_file = paste0(input.dir,'/../Workbook.html'))
unlink(paste0(input.dir,'/Workbook-tmp.Rmd'))
})
...but all squeezed onto 1 line!
The rest of the 'master'/'root'/'control' file or whatever you want to call it takes care of writing the aforementioned YAML for the final HTML output that goes via an intermediate Rmarkdown file, and its second code chunk programmatically appends child documents through a call to list.files()
```{r include=FALSE}
header.input.file <- "Workbook-header.yaml"
header.input.dir <- normalizePath(dirname(header.input.file))
fileConn <- file(header.input.file)
writeLines(c(
"---",
paste0('title: "', rmarkdown::metadata$title,'"'),
"output:",
" html_document:",
" toc: true",
" toc_depth: 3 # defaults to 3 anyway, but just for ease of modification",
" number_sections: TRUE",
paste0(" css: ",paste0(header.input.dir,'/../resources/workbook_style.css')),
' pandoc_args: ["--number-offset=1", "--atx-headers"]',
"---", sep="\n"),
fileConn)
close(fileConn)
```
```{r child = list.files(pattern = 'Notes-.*?\\.md')}
# Use file names with strict numeric ordering, e.g. Notes-001-Feb1.md
```
The directory structure would contain a top-level folder with
A final output Workbook.html
A resources subfolder containing workbook_style.css
A documents subfolder containing said main file "Workbook.Rmd" alongside files named as "Notes-001.Rmd", "Notes-002.Rmd" etc. (to ensure a fileglobbing on list.files(pattern = "Notes-.*?\\.Rmd) finds and thus makes them children in the correct order when rendering the main Workbook.Rmd file)
To get proper numbering of files, each constituent "Notes-XXX.Rmd" file should contain the following style YAML header:
---
title: "March: Doing x, y, and z"
knit: (function(inputFile, encoding) { input.dir <- normalizePath(dirname(inputFile)); rmarkdown::render(input = inputFile, encoding = encoding, quiet=TRUE)})
output:
md_document:
variant: markdown_github
pandoc_args: "--atx-headers"
---
```{r echo=FALSE, results='asis', comment=''}
cat("##", rmarkdown::metadata$title)
```
The code chunk at the top of the Rmarkdown document enters the YAML title as a second-level header when evaluated. results='asis' indicates to return plain text-string rather than
[1] "A text string"
You would knit each of these before knitting the main file - it's easier to remove the requirement to render all child documents and just append their pre-produced markdown output.
I've described all of this at the links above, but I thought it'd be bad manners not to leave the actual code with my answer.
I don't know how effective that RStudio feature request website may be... Personally I've not found it hard to look into the source code for these functions, which thankfully are open source, and if there really is something absent rather than undocumented an inner-workings-informed feature request is likely far more actionable by one of their software devs.
I'm not familiar with Sweave, was the above was what you were aiming at? If I understand correctly you just want to control the inclusion of documents in a modular fashion. The child = list.files() statement could take care of that: if not through file globbing you can straight-up list files as child = c("file1.md","file2md")... and switch that statement to change the children. You can also control TRUE/FALSE switches with YAML, whereby the presence of a custom header would set some children to be included for example
potentially.absent.variable: TRUE
...above the document with a silent include=FALSE hiding the machinations of the first chunk:
```{r include=FALSE}
!all(!as.logical(rmarkdown::metadata$potentially.absent.variable)
# ==> FALSE if potentially.absent.variable is absent
# ==> FALSE if anything other than TRUE
# ==> TRUE if TRUE
checkFor <- function(var) {
return !all(!as.logical(rmarkdown::metadata[[var]])
}
```
```{r child = "Optional_file.md", eval = checkFor(potentially.absent.variable)}
```
I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.
I'm writing an Rmd file, to be processed by knitr into HTML. It contains some R chunks that generate figures, which get stored as data URIs in HTML.
1) How do I add a caption to such an image? I'd like to have a caption that says something like "Figure 3: blah blah blah", where the "3" is automatically generated.
2) How do I later on reference this image, i.e., "as you can see in Figure 3, blah blah".
I'm late to the party, but I wanted to mention a small package I recently built to do figure captioning and cross-referencing with knitr. It is called kfigr and you can install it using devtools::install_github('mkoohafkan/kfigr'). It is still in active development but the main functionality is there. Be sure to check out the vignette, it shows some usage examples and defines some hooks for figure captions and anchors (I may later choose to have the package import knitr and define those hooks on load).
EDIT: kfigr is now available on CRAN!
You can create the figure numbers with a simple counter in R; see one example here. The problem is whether the markdown renderer will render the figure caption for you: R Markdown v1 won't, but v2 (based on Pandoc) will.
I do not know. There is no direct way to insert a label as an identifier for figures, so it is probably not possible to cross reference figures with pure Markdown. Once you've got issues like this, think (1) do I really need it? (2) if it is intended to be a document with a complicated structure, I think it is better to use LaTeX directly (Rnw documents).
Also very late to the party I changed Yihuis suggestion here that he also linked above to do referencing.
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
```{r cars, echo=FALSE, fig.cap=fig$cap("cars", "Here you see some interesting stuff about cars and such.")}
plot(cars)
```
What you always wanted to know about cars is shown in figure `r fig$ref("cars")`
One way to do both of these is described here: http://rmflight.github.io/posts/2012/10/papersinRmd.html
Another is described here (but I don't know if it does your #2). http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/
Another solution:
https://github.com/adletaw/captioner
From the README:
captioner() returns a captioner function for each set of figures, tables, etc. that you want to create. See the help files for more details.
For example:
> fig_nums <- captioner()
> fig_nums("my_pretty_figure", "my pretty figure's caption")
"Figure 1: my pretty figure's caption"
> fig_nums("my_pretty_figure", cite = TRUE)
I did both (figure numbers + references) with bookdown. I added in output section in the header of the file:
output:
bookdown::html_document2:
fig_caption : TRUE
Then I created a figure in a R code chunk like follows:
{r, my-fig-label,echo=F, eval=T, fig.align = 'center', fig.cap="This is my caption"}
knitr::include_graphics(here::here("images", "my_image.png"))
This produces an automatic number under your figure. You can refer to it with \#ref(fig:my-fig-label).
Using the official bookdown documentation 4.10 Numbered figure captions:
---
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r mtcars, fig.cap = "Another amazing plot"}
plot(mpg ~ hp, mtcars)
```