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:
Related
I have a somewhat complicated R function (different parts refer to various equations I'd like to explain.)
I want to write my code using R Markdown, but I need to be able to explain the different parts of the function in the document. A bit like literate programming.
I wonder if it is possible to split the function definition across different code chunks, or maybe insert markdown comments inside the function definition?
I'd like the end result to look something like this:
complicated = function(x) {
I use x^2 in the example so it is math, and yet short. Here it is in the actual R code:
x^2
}
This doesn't work:
``` {r}
complicated = function(x) {
```
explain the function with some math $x^$.
``` {r}
x^2
}
```
The following actually does work:
``` {r chunk1, echo=FALSE}
complicated=function(x) {
x^2
}
```
``` {r chunk1, echo=1:2, eval=F}
```
In the complicated function I use x^2 as an example.
Though it is a bit tricky, because if lines in the function change, I have to edit everything again. Also in the Rmd file, you don't actually see the code described by the comments.
Note:
Maybe it is possible to somehow have the relevant chunks written to a file without being evaluated, and then the file read in? I didn't manage to figure out a way yet...
Here's one way, though I admit it's a little bit of a hack.
---
title: "Split Function"
output: html_document
---
```{r funcdef}
myfunc <- function(x) {
x <- x + 1
x <- x * 2
return(x)
}
```
```{r funcdef1, echo = FALSE, eval = FALSE, include = FALSE}
x <- NULL
x <- x + 1
x <- x * 2
return(x)
```
First line:
```{r funcdef1, echo=2, eval = FALSE}
```
Now the last two:
```{r funcdef1, echo=3:4, eval = FALSE}
```
Done!
Explanation:
the first chunk funcdef is the full function definition, needed if we want to use it;
the second chunk includes the first line (that I do not echo, omitted with echo=-1) that is there so that the others do not err with 'x' not found (even if I do not eval or include); notice that it uses the same chunk name and has nothing in it
same for the third chunk
the reason I have to break out the body of the function without the function header and enclosing braces is that echo= using numbers allows us to subset which expressions are included, not which lines ... and a function declaration is one expression
Two things I don't really like about this:
It requires you to include the body of the function twice, so maintenance has more overhead than required;
It thinks x is being used, when all I really want is to reference the code.
Frankly, this may not be much better than including the portions of code within each subsequent chunk (and set eval=FALSE).
I found a nice answer to this question, though it looks a bit like a knitr bug. I hope it doesn't get fixed. It turns out that references to chunks work in Rmd just like in Rnw. You just have to use <<chunk name>> to refer back to a chunk.
So, here is the answer:
```{r Xsquare, eval=F}
x^2
```
We just need to take x and raise it to the second power: $x^2$.
Now let us put it together:
```{r complicated, eval=T}
complicated = function(x) {
<<Xsquare>>
}
```
Simple, right?
Turns out in Rstudio it works only when we knit everything together, but not on running a single chunk. Almost makes sense.
To solve this, in run the following: knit("filename.Rmd") in the console.
I want my html file to show the code, but not the output of this chunk:
```{r echo=True, include=FALSE}
fun <- function(b)
{
for(a in b)
{print(a)
return(a * a)}
}
y <- fun(b)
```
When I run the code, i need the print to see the progress (it is quite a long function in reality).
But in the knitr file, I use the output in a further chunk, so I do not want to see it in this one (and there's no notion of progress, since the code has already been run).
This echo=True, include=FALSE here does not work: the whole thing is hidden (which is the normal behavior of include=FALSE).
What are the parameters I could use to hide the prints, but show my code?
As # J_F answered in the comments, using {r echo = T, results = 'hide'}.
I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!
You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.
Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
results = "hide")
```
Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.
```{r analysis, results="markup"}
# code here
```
The results = 'hide' option doesn't prevent other messages to be printed.
To hide them, the following options are useful:
{r, error=FALSE}
{r, warning=FALSE}
{r, message=FALSE}
In every case, the corresponding warning, error or message will be printed to the console instead.
```{r eval=FALSE}
The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.
For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
To hide warnings, you can also do
{r, warning=FALSE}
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
I'm writing a report in R Markdown in which I don't want to print any of my R code in the main body of the report – I just want to show plots, calculate variables that I substitute into the text inline, and sometimes show a small amount of raw R output. Therefore, I write something like this:
In the following plot, we see that blah blah blah:
```{r snippetName, echo=F}
plot(df$x, df$y)
```
Now...
That's all well and good. But I would also like to provide the R code at the end of the document for anybody curious to see how it was produced. Right now I have to manually write something like this:
Here is snippet 1, and a description of what section of the report
this belongs to and how it's used:
```{r snippetName, eval=F}
```
Here is snippet 2:
```{r snippetTwoName, eval=F}
```
<!-- and so on for 20+ snippets -->
This gets rather tedious and error-prone once there are more than a few code snippets. Is there any way I could loop over the snippets and print them out automatically? I'm hoping I could do something like:
```{r snippetName, echo=F, comment="This is snippet 1:"}
# the code for this snippet
```
and somehow substitute the following result into the document at a specified point when it's knitted:
This is snippet 1:
```{r snippetName, eval=F}
```
I suppose I could write some post-processing code to scan through the .Rmd file, find all the snippets, and pull out the code with a regex or something (I seem to remember there's some kind of options file you can use to inject commands into the pandoc process?), but I'm hoping there might be something simpler.
Edit: This is definitely not a duplicate – if you read my question thoroughly, the last code block shows me doing exactly what the answer to the linked question suggests (with a slight difference in syntax, which could have been the source of the confusion?). I'm looking for a way to not have to write out that last code block manually for all 20+ snippets in the document.
This is do-able within knitr, no need to use pandoc. Based on an example posted by Yihui at https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw
Set echo=FALSE throughout your document: opts_chunk$set(echo = FALSE)
Then put this chunk at the end to print all code:
```{r show-code, ref.label=all_labels(), echo = TRUE, eval=FALSE}
```
This will print code for all chunks. Currently they all show up in a single block; I'd love to figure out how to put in the chunk label or some other header... For now I start my chunks with comments (probably not a bad idea in any case).
Updated: to show only the chunks that were evaluated, use:
ref.label = all_labels(!exists('engine')) - see question 40919201
Since this is quite difficult if not impossible to do with knitr, we can take advantage of the next step, the pandoc compilation, and of pandoc's ability to manipulate content with filters. So we write a normal Rmd document with echo=TRUE and the code chunks are printed as usual when they are called.
Then, we write a filter that finds every codeblock of language R (this is how a code chunk will be coded in pandoc), removes it from the document (replacing it, here, with an empty paragraph) and storing it in a list. We then add the list of all codeblocks at the end of the document. For this last step, the problem is that there really is no way to tell a python filter to add content at the end of a document (there might be a way in haskell, but I don't know it). So we need to add a placeholder at the end of the Rmd document to tell the filter to add the R code at this point. Here, I consider that the placeholder will be a CodeBlock with code lastchunk.
Here is the filter, which we could save as postpone_chunks.py.
#!/usr/bin/env python
from pandocfilters import toJSONFilter, Str, Para, CodeBlock
chunks = []
def postpone_chunks(key, value, format, meta):
if key == 'CodeBlock':
[[ident, classes, keyvals], code] = value
if "r" in classes:
chunks.append(CodeBlock([ident, classes, keyvals], code))
return Para([Str("")])
elif code == 'lastchunk':
return chunks
if __name__ == "__main__":
toJSONFilter(postpone_chunks)
Now, we can ask knitr to execute it with pandoc_args. Note that we need to remember to add the placeholder at the end of the document.
---
title: A test
output:
html_document:
pandoc_args: ["--filter", "postpone_chunks.py"]
---
Here is a plot.
```{r}
plot(iris)
```
Here is a table.
```{r}
table(iris$Species)
```
And here are the code chunks used to make them:
lastchunk
There is probably a better way to write this in haskell, where you won't need the placeholder. One could also customize the way the code chunks are returned at the end to add a title before each one for instance.
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.
-->