I want to use knitr hooks on individual chunks using the datacamp/tutorial package. As per the following document, I get to set two options of height and greedy by using tutorial::go_interactive(greedy=FALSE, height=500)
How can I set different variables for individual chunks using knitr_hooks?
For eg., For the first chunk I want to set it up as greedy=TRUE, and for the second one, I want greedy=FALSE.
---
title: "Example Document"
author: "Your name here"
output:
html_document:
self_contained: false
---
```{r, include=FALSE}
tutorial::go_interactive()
```
Here's an example of a Python fiddle/
```{python}
a = 2
b = 3
print(a + b)
```
```{python}
x = 2
y = 3
print(x + y)
```
Never mind. Found the answer here
You have to set tut = FALSE on the chunk to knit it as a normal chunk.
```{r, include=FALSE}
tutorial::go_interactive()
```
Here's an example of a Python fiddle/
```{python}
a = 2
b = 3
print(a + b)
```
```{python, tut=FALSE}
x = 2
y = 3
print(x + y)
```
Related
I want to add the table of content in different place instead of the first page in .Rmd pdf. I found the function render_toc() from #Garrick Aden-Buie this is the link https://gist.github.com/gadenbuie/c83e078bf8c81b035e32c3fc0cf04ee8. It is working perfect if I don't use cat() in chunk codes.
I have to use cat() in my .Rmd, is there any way I can add the table of contents any place in .Rmd
You can see the table of contents only test 1, test 2, and test 3, setosa, versicolor, virginica did not include in table of content
---
title: "test"
output:
pdf_document:
number_sections: yes
toc: yes
toc_depth: 4
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
source("render_toc.R")
library(knitr)
```
\newpage
# Table of Contents {#crazy-slug-here}
```{r echo = FALSE}
render_toc("test.Rmd")
```
# Test 1
# Test 2
# Test 3
```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
cat('\n#', Species, '\n')
p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
cat('\n')
}
```
Using the code you provided I'm able to knit the pdf document and get the three plots, one for each Species in iris.
This code, however, produces two TOCs: one of them in the first page which is not desired according to your question. In order to get only the TOC produced by the function render_toc() set toc: no in the YAML header.
---
title: "test"
output:
pdf_document:
number_sections: yes
toc: no
toc_depth: 4
---
This way only one TOC will be generated and placed where render_toc() is.
Edit: After seeing your edit with the desired output, I think the following LaTeX code can help:
\newpage
\thispagestyle{plain}
\mbox{}
\setcounter{tocdepth}{2}
\renewcommand{\contentsname}{Table of Contents}
\tableofcontents
\newpage
\thispagestyle{plain}
\mbox{}
Note: here we are not using render_toc(). The code creates the TOC in the second page of the document. If you need another blank page, just introduce another block of:
\newpage
\thispagestyle{plain}
\mbox{}
These pages may or may not be numbered, which you control via the argument passed to \thispagestyle{}. See here for more details.
Full code:
---
title: "Document title"
output:
pdf_document:
number_sections: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newpage
\thispagestyle{plain}
\mbox{}
\setcounter{tocdepth}{2}
\renewcommand{\contentsname}{Table of Contents}
\tableofcontents
\newpage
\thispagestyle{plain}
\mbox{}
# Test 1
## Subsection 1
# Test 2
## Subsection 2
# Test 3
```{r, results='asis', echo=FALSE}
library(ggplot2)
for(Species in levels(iris$Species)){
cat('\n#', Species, '\n')
p <- ggplot(iris[iris$Species == Species,],
aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
cat("\n")
}
```
This way we end up with a TOC looking like this:
When using bookdown (single document), if I set both section_numbering = 'yes' and fig_caption = 'yes', the figures are numbered X.2 (where X is the section number). If section_number = 'no', the figures are numbered sequentially (Fig 1, 2 ...), but sections numbers are lost.
Is there a way to get figures numbered sequentially without losing the section numbers? In the example below, I would like to have both the sections figures numbered as 1 and 2.
Thank you.
---
output:
bookdown::html_document2:
fig_caption: yes
number_sections: yes
---
# header 1
Reference example: \#ref(fig:plotcars):
```{r plotcars, fig.cap = "A car plot"}
plot(cars)
```
# header 2
Reference example: \#ref(fig:plotcars2):
```{r plotcars2, fig.cap = "A car plot"}
plot(cars)
```
I just added a new argument global_numbering to the dev version of bookdown. You can test the dev version via
remotes::install_github('rstudio/bookdown')
Example:
---
output:
bookdown::html_document2:
fig_caption: true
number_sections: true
global_numbering: true
---
# header 1
Reference example: \#ref(fig:plotcars):
```{r plotcars, fig.cap = "A car plot"}
plot(cars)
```
# header 2
Reference example: \#ref(fig:plotcars2):
```{r plotcars2, fig.cap = "A car plot"}
plot(cars)
```
Following this and this stackoverflow-questions, I tried to use knit-child inside a loop, containing a variable-defined title.
Instead of the variables (e.g. A, B, C) as title, I get them with # still attached (# A, # B, # C)
Parent:
---
title: "Untitled"
output: html_document
---
```{r,include=FALSE}
library(knitr)
```
```{r,echo=FALSE}
titles<-LETTERS[1:3]
```
```{r,include=FALSE,echo=FALSE}
out = NULL
for (i in titles){
out = c(out, knit_child('Child.Rmd'))
}
```
`r paste(out, collapse='\n')`
Child:
---
title: "Untitled"
output: html_document
---
```{r,echo=FALSE,results='asis'}
cat("\n\n # ", i,"\n")
```
```{r,echo=FALSE,results='asis'}
cat("\n\n This text is about ", i,"\n")
```
Output:
While I would prefer:
The # character only indicates a heading in markdown if it is the first character of the line.
cat("\n\n # ", i,"\n") produces two new lines, then one space and then the #. Remove the whitespace to fix the issue:
cat("\n\n# ", i,"\n")
Consider using pandoc.headerinstead of Cat.
i = 1
pander::pandoc.header(i, level = 1)
> # 1
pander::pandoc.header(paste0("Subheading ", i), level = 3)
> ### Subheading 1
I recommend using the knit_expand function.
You create your Child.Rmd as
# {{current_title}}
This text is about {{current_title}}
Remember that `current_title` is a literal string, so
if you want use it in code then must be quoted:
<!-- Use `current_title` in chunk name to avoid duplicated labels -->
```{r {{current_title}}}
data.frame({{current_title}} = "{{current_title}}")
```
Then your main document shoud looks like this:
---
title: "Untitled"
output: html_document
---
```{r,include=FALSE}
library(knitr)
```
```{r,echo=FALSE}
titles<-LETTERS[1:3]
```
```{r,include=FALSE,echo=FALSE}
expanded_child <- lapply(
titles
,function(xx) knit_expand("Child.Rmd", current_title = xx)
)
parsed_child <- knit_child(text = unlist(expanded_child))
```
`r parsed_child`
Results:
I want to set the chunk option "eval" based on a list of chunk names. Is there a function to get the chunk name in knitr, e.g. chunk_name?
This is my minimum example with fake function name "chunk_name".
---
output: html_document
---
```{r setup}
eval_chunks <- c('chunk1')
```
```{r chunk1, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
```{r chunk2, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
Thanks for any suggestions. Please let me know if my question is not clear.
Knitr provided labels inside a chunk since 2012 (need more Google, https://github.com/yihui/knitr/issues/73).
This is my sample Rmd file:
---
output: html_document
---
```{r setup}
library(knitr)
eval_chunks <- c('chunk1', 'chunk3')
```
```{r chunk1, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk2, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk3, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
I think this solution is imperfect because it requires a bit of care in making sure the correct chunks are evaluated, but it gets around the problem that chunk options are evaluated before hooks are called. In short, it doesn't use a hook, but instead uses the fact that chunk options can be R expressions. In this case, a function e() is used that relies on a global counter variable to dictate whether a particular chunk should be evaluated. Because chunks are evaluated in order, this works. In the below example, chunk1 and chunk3 are evaluated, but the others are not.
---
output: html_document
---
```{r setup}
library("knitr")
.i <- 2 # `setup` is the first chunk, so start at 2
.x <- all_labels() %in% c("chunk1", "chunk3")
e <- function(){
d <- .x[.i]
.i <<- .i + 1
d
}
```
```{r chunk1, eval=e()}
x <- 1
x
```
```{r chunk2, eval=e()}
x <- 2
x
```
```{r chunk3, eval=e()}
x <- 3
x
```
```{r chunk4, eval=e()}
x <- 4
x
```
I am writing on a presentation using Knitr, Markdown and Slidify. The slides will be partly deal with Knitr as topic which is the reason why I stumbeld upon a problem. I cannot include for example a knitr-markdown chunk to show it on the slide. It will always be interpreted on the first run even if I do something like this:
```
```{r eval = F, include = T}
```
```
How can I prevent a chunk to be interpreted and thus removed from the final output so that I can show how a chunk is structured when using Markdown and Knitr?
EDIT:
I tried the version of you #Ramnath and made up te following slides:
## Testslide 1
```{r verbatimchunk, verbatim = TRUE}
x = 1 + 1
x
```
```{r regularchunk}
x = 1 + 1
x
```
---
## Testslide 2
```{r verbatimchunk_2, verbatim = TRUE}
x = 1 + 1
x
```
* element 1
* element 2
---
## Testslide 3
* element 1
* element 2
```{r verbatimchunk_3, verbatim = TRUE}
x = 1 + 1
x
```
The first two slides work fine but the last one is the problem. If there is a bullet list before the verbatim chunk, it is interpreted as usual. So it is the same as with the first solution from #Scott. I do not understand this.
EDIT 2/3 (Working solution)
```{r echo = FALSE}
require(knitr)
hook_source_def = knit_hooks$get('source')
knit_hooks$set(source = function(x, options){
if (!is.null(options$verbatim) && options$verbatim){
opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
bef = sprintf('\n\n ```{r %s}\n', opts, "\n")
stringr::str_c(bef, paste(knitr:::indent_block(x, " "), collapse = '\n'), "\n ```\n")
} else {
hook_source_def(x, options)
}
})
```
## Testslide
* Element one
* Element two
Some text here breaks list environment:
```{r verbatim = T}
any code
```
Here is another solution that makes use of chunk hooks. The idea is that if you have a chunk with option verbatim = TRUE, it activates the hook and outputs the chunk verbatim. I have checked that it works with Slidify too.
```{r echo = FALSE}
require(knitr)
hook_source_def = knit_hooks$get('source')
knit_hooks$set(source = function(x, options){
if (!is.null(options$verbatim) && options$verbatim){
opts = gsub(",\\s*verbatim\\s*=\\s*TRUE\\s*", "", options$params.src)
bef = sprintf('\n\n ```{r %s}\n', opts, "\n")
stringr::str_c(bef, paste(knitr:::indent_block(x, " "), collapse = '\n'), "\n ```\n")
} else {
hook_source_def(x, options)
}
})
```
```{r verbatimchunk, verbatim = TRUE}
x = 1 + 1
x
```
```{r regularchunk}
x = 1 + 1
x
```
EDIT: The trick with code chunks after a list is that the list environment needs to be broken. A quick and dirty way is just to add an empty paragraph element. Alternately, you can fix the hook so that en empty paragraph is automatically added at the beginning of the code chunk.
* element 1
* element 2
<p></p>
```{r verbatimchunk_3, verbatim = TRUE}
x = 1 + 1
x
```
I think you need to add an empty string after ```{r}, and knitr will not execute the chunk, but will display it. See the example here
This on a slide works for me (where the top one executes and the bottom does not)
---
```{r}
list(5, 6, 7)
```
```{r}`r ''`
hist(rnorm(100))
5 + 6
```
---
Very late to the party, but this also seems to work:
```{r echo=FALSE, class.output="r", comment=""}
cat("```{r}\nx <- 1 + 1\nx\n```")
```
Or, equivalent but perhaps nicer to read and write:
```{r echo=FALSE, class.output="r", comment=""}
cat(paste(sep = "\n",
"```{r}",
"x <- 1 + 1",
"x",
"```"
))
```