Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

r - Conditionally display block of markdown text using knitr

I would like to edit a single rmarkdown (Rmd) document with a list of "problems", each followed by its solution. Each solution may contain the results of R console, but also some explaining (markdown and LaTeX formatted) text. Besides, I would like to knitr it in 2 versions: with and without the solutions, changing the source as less as possible, and compiling.

I know I can use a logical variable in order to conditionally evaluate R code and show plots and R output, but I don't know how to show/hide blocks of (markdown and LaTeX) formatted text, unless I put all that text into R character vectors, which seems hard in order to keep things clean and readable.

I found old question

Conditionally display a block of text in R Markdown

where the solution was given for simple short text, which was included as an argument of the R print() function.

This other old question

insert portions of a markdown document inside another markdown document using knitr

was for having a father document and child documents which were conditionally compiled, but I don't want to slice my document into so many pieces.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.

```{asis, echo=FALSE}
Some arbitrary text.

1. item
2. item

Change echo=TRUE or FALSE to display/hide this chunk.
```

But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
  if (options$echo && options$eval) paste(options$code, collapse = '
')
})
```

If you want to include inline R expressions in the text, you will have to knit the text, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
  if (options$echo && options$eval) knit_child(text = options$code)
})
```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...