问题
I currently have a subset of figures in Rmarkdown but would like to hide or display them by specifying echo = F
or echo = T
for those only. It is tedious to go through each of the figures I want to hide or display and change the echo option. Is there a global way of toggling or making certain figures show? In other words, is there a way to perhaps do:
```{r, echo.func}
include.graphics("this/plot/shows.jpg")
```
and be able to somehow control echo.func
to be equal to echo = F
or echo = T
in the beginning? Thanks!
回答1:
The argument to echo=
can be a full expression, so you can define classes or individual blocks. Something like this:
---
title: echo test
output: html_document
---
```{r setup, echo = FALSE, include = FALSE}
echolist <- c("plots", "table2")
```
```{r table1, echo = any(c("tables", "table1") %in% echolist)}
# mtcars[1:3,]
```
```{r plot1, echo = any(c("plots", "plot1") %in% echolist)}
# plot(1)
```
```{r table2, echo = any(c("tables", "table2") %in% echolist)}
# mtcars[5:10,]
```
```{r plot2, echo = any(c("plots", "plot2") %in% echolist)}
# plot(2)
```
From this, I think it'd be feasible to write a function that you pass the block name (e.g., {r blockname, echo=checkecho("blockname")}
), and internally it does something that perhaps checks literal titles, patterns, groups, etc.
Suggestion for functionizing it:
---
title: echo test
output: html_document
---
```{r setup, echo = FALSE, include = FALSE}
.checkecho <- function(nm) {
any(c(nm, gsub("\\d+$", "s", nm)) %in% c("plots", "table2"))
}
```
```{r table1, echo = .checkecho("table1")}
# mtcars[1:3,]
```
```{r plot1, echo = .checkecho("plot1")}
# plot(1)
```
```{r table2, echo = .checkecho("plot2")}
# mtcars[5:10,]
```
```{r plot2, echo = .checkecho("table2")}
# plot(2)
```
The biggest take-away from this is for you to come up with a naming standard that will facilitate your job. In this example:
- everything starts with a simple description of expected output and ends with a number (which does not need to be incrementing *shrug*);
- you can control individual echo-ing by specifying specific blocks or by removing the number and adding an "s"
You can easily turn this into a negation policy instead, where you turn off specific elements ... the possibilities are numerous and probably why there is not already a function in rmarkdown
or knitr
that facilitates this.
(If you're curious ... I chose to start the function name with a dot so that, if for some reason you include the output from ls()
in your report, the function will not be included. To see it, you'd need to do ls(all.names=TRUE)
. *shrug*)
来源:https://stackoverflow.com/questions/57436988/is-there-a-way-to-specify-a-global-options-chunk-function-in-rmarkdown-so-that-o