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:
Related
I am making a table with reactable in R markdown and I want a column group with a line break. Minimal example is here:
---
output: pdf_document
---
```{r, echo=F}
library(reactable)
data = mtcars[1:4, 1:4]
reactable(
data,
columnGroups = list(colGroup(name = "This is Line 1 of the group name \\ This is Line 2 of the group name", columns=names(data)))
)
Note that the \\ just gets printed in the final output. I've tried other HTML-y things like <br /> and \n and they get printed in the final output too.
Any thoughts?
Thanks!
If you're not opposed to using kableExtra:
You'll have to make two changes:
Add the header-includes option to your yaml at the top.
Change the reactable code to kable
---
title: "test"
output: pdf_document
header-includes:
- \usepackage{caption}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo = F}
library(kableExtra)
data = mtcars[1:4, 1:4]
kable(
data,
caption = "This is Line 1 of the group name\\\\This is Line 2 of the group name"
)
```
This gives us:
You can format it with other kableExtra functions if you want horizontal/vertical lines, specific column widths, etc.
Similar to how to create a loop that includes both a code chunk and text with knitr in R i try to get text and a Code snippet created by a Loop.
Something along this:
---
title: Sample
output: html_document
params:
test_data: list("x <- 2", "x <- 4")
---
for(nr in 1:3){
cat(paste0("## Heading ", nr))
```{r, results='asis', eval = FALSE, echo = TRUE}
params$test_data[[nr]]
```
}
Expected Output would be:
What i tried:
I tried to follow: https://stackoverflow.com/a/36381976/8538074. But printing "```" did not work for me.
You can make use of knitr hooks. Take the following MRE:
---
title: "Untitled"
output: html_document
params:
test_data: c("x <- 2", "x <- 4")
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, results = 'asis', echo = F}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()
chunks <- eval(parse(text = params$test_data))
for(nr in seq_along(chunks)){
cat(paste0("## Heading ", nr, "\n"))
cat(hook(chunks[nr], options = opts))
}
```
We get the default source hook and also the default chunk options. Then we get the test data, which is supplied as a string. Therefore we parse and evaluate that string.
In the loop we simply call the source hook on each element of the test data. Here is the result:
Im new to Rmarkdown and I would like to create dynamic reports where every report section is generated from a template (child) document. Each section will then start with a newpage in the rendered pdf.
My approach is currently based on this post which shows how to generate dynamically text in the child (which works), however I am not able to transfer the contents of the loop into a R-Codeblock, probably because the params are not well defined in the way that I tried to do it.
This is how my parent document looks like:
---
title: "Dynamic RMarkdown"
output: pdf_document
---
```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```
# Automate Chunks of Analysis in R Markdown
Blahblah Blabla
\newpage
```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
out = c(out, knit_expand('template.Rmd'))
params <- list(species = i)
}
```
`r paste(knit(text = out), collapse = '\n')`
and this is how the child looks like
---
title: "template"
output: html_document
params:
species: NA
---
# This is the reporting section of Species {{i}}
This is a plot of Sepal length and width based on species {{i}}.
```{r plot2}
paste(params$species)
# plot doesnt work work
# plot(iris$Sepal.Length[iris$Species=={{i}}],
# iris$Sepal.Width[iris$Species=={{i}}]
# )
```
\newpage
To my understanding the parameter that is actually passed is the last species from the dataset generated in the loop but I'm not sure why the plot would't work then. Can anybody help me out on how to fix this issue?
Ok. No need to go through params. The solution was simply to put i between brackets AND parenthesis in the child-document.
Parent:
---
title: "Dynamic RMarkdown"
output: pdf_document
---
```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```
# Automate Chunks of Analysis in R Markdown
Blahblah Blahblah Main text before individual sections
\newpage
```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
out = c(out, knit_expand('template.Rmd'))
}
```
`r paste(knit(text = out), collapse = '\n')`
Child
---
title: "template"
output: html_document
---
# This is the reporting page of Species {{i}}
This is a plot of Sepal length and width based on species {{i}}.
```{r plot2}
paste("This will be a plot of Sepal Length and Witdh from", '{{i}}')
plot(iris$Sepal.Length[iris$Species=='{{i}}'],
iris$Sepal.Width[iris$Species=='{{i}}']
)
```
\newpage
Original solution found here.
I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.
For example
---
title: "test"
output: pdf_document
---
```{r, results='asis'}
for (i in 1:10) {
cat("\\section{Part:", i, "}")
summary(X)
$\alpha = `r X[1,i]`$
}
```
pretty much does the trick, but here there are still two problems:
the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible
Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?
I am very thankful for every kind of advice
You can do what you are after inline without relying as much on code blocks.
As a minimal example.
---
title: "test"
output: pdf_document
---
```{r sect1_prep, include=FALSE}
i <- 1
```
\section{`r paste0("Part: ", i)`}
```{r sect1_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
```{r sect2_prep, include=FALSE}
i <- i + 1
```
\section{`r paste0("Part: ", i)`}
```{r sect2_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
Produces...
If you really want to have a section factory, you could consider pander.
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
empty <- lapply(1:10, function(x) {
pandoc.header(paste0("Part: ", x), level = 2)
pander(summary(mtcars[, x]))
pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))
})
```
which produces...
remove summary table format example
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
content <- lapply(1:10, function(x) {
head <- pandoc.header.return(paste0("Part: ", x), level = 2)
body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))
return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))
})
writeLines(unlist(content), sep = "\n\n")
```
Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:
---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document
---
```{r}
# Generate some data
rnorm(2)
## But keep this comment
```
When kniting I would like the first comment to disapear, but keep the second one somehow.
Here is a quick example of modifying the hook to change knitr behavior.
---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---
```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
x <- x[!grepl("^#\\s+", x)]
paste0("```r\n",
paste0(x, collapse="\n"),
"\n```")
}
knitr::knit_hooks$set(source = hook_in)
```
```{r}
# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents
rnorm(2)
## But keep this comment
## But lines that starts with `## ` will be kept
```
produces this
In fact, you can choose to show any lines of R code by passing numeric indices to the chunk option echo, e.g.
---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document
---
```{r echo=4:7}
# Generate some data
rnorm(2)
## But keep this comment
```
See knitr documentation for more information.