How should I code solutions to exercises in the book I am writing using the bookdown package?
I'm currently writing a book using the bookdown R package. The book is broken down into chapters, and each chapter has exercises in a markdown numbered list. I would like to be able to put the solutions directly under the exercises without messing up the numbering of the problems, and in such a way that I can toggle whether the solutions are printed. I would also like to be able to pull out selected solutions (or all solutions) to form a solutions manual that gets printed out as an appendix. So far, I have two methods, which I call the "hidden R chunk method" and the "YAML method" but neither seems ideal, and can only be used to create a solutions manual.
1. Exercise one compute 1+1.
```{r, echo = FALSE, eval = FALSE}
#Solution
1+1
#BeginText The solution is `r 1 + 1`.
#EndText
```
1. Exercise two: compute 2^2.
```{r, echo = FALSE, eval = FALSE}
#Solution
2*2
#BeginText The solution is $2^2 = $`r 2*2`.
#EndText
```
I then wrote a script that pulls out anything with the #Solution comment, and breaks the #BeginText and #EndText out like this:
###Problem 1.
```{r }
1+1
```
The solution is `r 1 + 1`.
###Problem 2.
```{r }
2*2
```
The solution is $2^2 = $`r 2*2`.
and saves that in a new .Rmd file with appropriate headers.
The second solution involves YAML in between the exercises.
1. Exercise one compute 1+1.
---
solution: |
```{r}
1+1
```
The solution is `r 1 + 1`.
---
My co-author had hoped that he could pull out the YAML using an existing parser, but ended up having to write a script just like the hidden R chunk method. I'm not sure how bad of an idea it is to use YAML like this. Both solutions require that each exercise have at least a solution stub in order for the numbering to be the same.
I would like the solutions of the exercises to be connected to the exercise in some way, so that if we re-arrange the exercises or add new exercises, nothing breaks. I would also like to be able to pull out some or all of the solutions into separate markdown files that we can use to create a solutions manual.
How should we do this?
Related
I'm in the midst of writing a textbook. I frequently use custom code blocks to explain technical concepts. These are quite nice, but sometimes I want to embed an r chunk within a custom code block. As an example, I would like to do the following:
```{block, type="rmdnote"}
This is a very tricky concept to master. Let's look at a plot and output generated from R:
```{r, echo=FALSE}
plot(1:10, 1:10)
summary(1:10)
```
```
This will not work. Is there any way to embed an r chunk within a custom chunk?
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 not sure it is the proper place for such a question. Eventually, tell me and I will delete it.
Imagine a colleague with limited technological competences. No competences on R at all. Is there a way or a command that allows to create an R Markdown html (with the Knitr package) output which accepts comments in the similar way of a text editor?
The matter has no mention on the website of R markdown http://rmarkdown.rstudio.com/ nor on of the Knitr package http://yihui.name/knitr/.
Not sure such functionality exists, but I could think about how this could be emulated
Abusing links, and have browser configuraion which shows link on hovering,
and maybe make such links in different color (linkcolor class?)
[MM](another bad idea)
Abusing R code, you'll get code rectangle with just a text
```{r, echo=TRUE, eval=FALSE}
MM: another bad idea
```
Abusing some R package which generates inlined HTML, say xtable
```{r results="asis", echo=FALSE}
comments.df <- data.frame(c("WHO", "MM"), c("CMT", "Another bad idea"))
print(xtable(comments.df), type = "html", include.rownames = FALSE)
```
Frankly, would be interested in the better answer, really good question...
In R, using knitr, is there a way to prevent line breaks in the HTML when results='hide' and echo=FALSE?
In this case:
First I do this,
```{r results='hide', echo=FALSE}
x=4;x
```
then I do that.
I get:
First I do this,
then I do that.
with both a break and an extra line between.
I'd like to get:
First I do this, then I do that.
instead.
Generally speaking, I'd like for code chunks to not insert new lines so that markdown is free to eat the one after the first line of text.
Thanks,
I assume you're creating an HTML document from an R Markdown document. In that case, you can use the inline R code capability offered by knitr by using the ` characters starting with the letter r.
Example:
In your R Markdown, write:
First I do this,`r x=4` then I do that. I can call x by doing `r x`.
And as output, you get:
First I do this, then I do that. I can call x by doing 4.
Note that in my example, I evaluated the variable x, but if you do not want to evaluate it, you do not have to. The variable x should still be assigned a value of 4 from the
`r x=4`
part of the R Markdown.
This is Inline R Code, and is documented here under the section "Inline R Code".
EDIT:
Note that Inline R Code has properties that are analogous to "echo=FALSE". And if you want to hide the results from inline R code, you can use base R functions to hide the output. See this question.
Try something like:
``` {r , results="asis", echo=F, eval=T}
if(showMe){
cat("printed")
} else {
cat("<!-- no break line -->")
}
```
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)
```