Rmd/Bookdown sharing sections/etc between Rmd documents - r

You have 2 documents: 1) Commercial and 2) Technical
The two should never diverge in the following sense:
Anything in the Commercial document must, verbatim, be in the technical document.
Is anything like the following possible in R by using Rmd/Bookdown?
In the spirit of "writing the code you wish you had":
Commercial.Rmd
```{r child = 'chapter_01.Rmd'}
```
Ch_01.Rmd:
## Section A
This is the sales by quarter:
```{r sales_by_quarter, results='asis'}
```
Technical.Rmd
```{r child = 'chapter_01_technical.Rmd'}
```
chapter_01_technical.Rmd:
</ Some magic to pull in 'Section A' from 'chapter_01.Rmd' \>
### Technical subsection
We define sales according to .... and handle missing data ...
```r sales_missing_data_summary
```
I am aware of the following:
Including a document in another
```{r child = 'chapter1.Rmd'}
```
Including R code
```{r shared_code}
```
Where the code is defined in shared.R:
#shared.R
#This code snippet is included in multiple places
## #knitr shared_code
a <- 10
b <- 0.05

Related

Rmarkdown backticks inside inline code / inconsistent behavior with usual code chunks

This works in a usual code chunk in R markdown:
m1_aov <- anova(m1)
m1_aov$`Sum Sq`[2] %>% round(3)
Unfortunately, using the latter in inline code breaks the knitr parser down
`r m1_aov$`Sum Sq`[2] %>% round(3)`
Indeed, it also breaks Stackoverflow.
I looked at this related question but could not infer a working solution to my problem. Any hint?
Expanding the comment with a working example:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
a <- tibble::tibble(`a column` = 1:10) # using tibble to get a column name with a white space
m <- mean(a$`a column`)
```
Mean is `r m`
To me this looks like a neat trick because it avoids to include unecessary long code inside the text, and do not create the problem you are facing at the (small) cost of creating new objects.
The output:

How can I create a conditional flexdashboard layout

The aim is to create a flexdashboard layout in an markdown file. File is in rows orientation and then the layout contains multiple rows one under another. The goal is to have one of the layout section and accompanying chunk not executed/displayed based on a predefined boolean condition. I was able to incorporate a boolean to not include the chunk code in output but can't find any results on a conditional layout.
Things to note the final result is a standalone file so shiny solutions are not possible. AFAIK
Current Result and needed result
What I've come up with so far just keeps the layout there with the title instead of removing everything.
the variable series35 is what is being used as a boolean to make the chunk not produce results. How can the
`row`
`--------------------------------------`
lines also be conditionalised (if that's a word) aka not create a new layout section when series35 is FALSE
row
-------------------------------------
###`r Title 1`
```{r, echo=FALSE, results='asis'}
chunk code
```
row
-------------------------------------
###`r Title 2`
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
row
-------------------------------------
###`r Title 3`
```{r, echo=FALSE, results='asis'}
chunk code
```
row
-------------------------------------
###`r Title 4`
```{r, echo=FALSE, results='asis'}
chunk code
```
row {data-height=50}
-------------------------------------
I ended up after much more searching finding a knitr question that gave me a solution
```{r, eval = series35}
asis_output("row")
asis_output("-------------------------------------")
asis_output("###`Title 2`")
```
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
It worked nicely as a quick addition. I didn't try joshpk's method as yet but it does seem like a potentially clean option.
You can wrap that section in comments that are controlled by your series35. Something like this (if you can provide a reproducible example then it will be easier to provide something that meets your requirements but hopefully this helps).
`r if(series35 == FALSE) {"\\begin{comment}"} else {NULL}`
###`r Title 2`
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
`r if(series35 == FALSE) {"\\end{comment}"} else {NULL}`

Inserting code chunks from one Rmarkdown document into another

I have been running some small R tutorials / workshops for which I keep my 'challenge scripts' in Rmarkdown documents. These contain free text and R-code blocks. Some of the code blocks are prefilled (eg, to set up datasets for later use), whereas some are there for the attendees to fill-in code during the workshop.
For each challenge script, I have a solution script. The latter contains all the free text of the former, but any challenge-blocks have been filled in (there's an example of a solutions workbook here).
I don't really want to keep two closely related copies of the same file (the challenge and the solutions workbook). So I was wondering if there's an easy way to construct my challenge scripts from my solutions scripts (or the solutions script from a challenge-script and an R-script containing just the solution blocks).
For example, is there an easy way to replace all named code-blocks in one Rmarkdown file with the correspondingly-named code block from another rmarkdown file?
That is, if I have
challenge.Rmd
HEADER
INTRODUCTION
Today we're going to learn about sampling pseudo-random numbers in R
```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled
# normally-distributed values
```
BLAH BLAH
END_OF_FILE
solutions.Rmd
HEADER
```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled
# normally-distributed values
hist(rnorm(100))
```
END_OF_FILE
How do I replace challenge_1 from challenge.Rmd with challenge_1 from solutions.Rmd?
All the best
This is one approach:
challenge.Rmd
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
show_solution <- FALSE
```
```{r child="solution.Rmd", eval=show_solution}
```
Today we're going to learn about sampling pseudo-random numbers in R
```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled
# normally-distributed values
```
```{r challenge_1_s, eval=show_solution, echo=show_solution}
```
```{r challenge_2}
# Challenge 2: Make a histogram of 100 randomly-sampled
# uniform-distributed values
```
```{r challenge_2_s, eval=show_solution, echo=show_solution}
```
solution.Rmd
```{r challenge_1_s, eval=FALSE, echo=FALSE}
# Challenge 1: Make a histogram of 100 randomly-sampled
# normally-distributed values
hist(rnorm(100))
```
```{r challenge_2_s, eval=FALSE, echo=FALSE}
# Challenge 2: Make a histogram of 100 randomly-sampled
# uniform-distributed values
hist(runif(100))
```
With the show_solution parameter you can include or exclude the solution from you rmarkdown. The participants are not able to compile the document for show_solution = TRUE unless they have the solution.Rmd. For show_solution = FALSE there's no problem and it compiles nicely.

Knitr output differs between Rmd and Rnw: data.table output example

Revised title to clarify focus.
We notice an anomaly that R markdown and data.table interact in a surprising way. Same does not happen when knitting LaTeX. Commands which not have a return within the R session do cause a return within the knitted markdown output. I trace the problem back to commands like the following, which do not produce an output in R,
````{r}
poolballs[ , weight2:=2 * weight]
```
but inside Rmarkdown, the output includes the full print of the poolballs DT. Same does not happen if we knit an equivalent chunk in LaTeX.
This produced some funny HTML output because I wrote chunks like this, intending to display only the first 5 lines
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Markdown parses that as the equivalent of two chunks,
> poolballs[ , weight2:=2 * weight]
> poolballs
> head(poolballs)
Here's the markdown file to demonstrate
---
title: "Data Table Guide"
author:
- name: Paul Johnson
affiliation: Center for Research Methods and Data Analysis, University of Kansas
email: pauljohn#ku.edu
date: "`r format(Sys.time(), '%Y %B %d')`"
output:
html_document:
theme: united
highlight: haddock
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=TRUE, comment=NA)
options(width = 70)
```
```{r make_pb_dt}
set.seed(234234)
library(data.table)
poolballs <- data.table(
number = 1:15,
weight = rnorm(15, 45.7, 0.8),
diameter = c(3, 2.9, 3.1) #shows recyling
)
poolballs
```
I want the following to show only head in line 2
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Compare the HTML output:
http://pj.freefaculty.org/scraps/mre-dt.html
I'm sorry if this is a known feature of markdown. I've coded around this wrinkle by hiding chunks, but it seems somewhat inconvenient. Today i'm curious enough to ask you about it. I wrote the same chunks in a LaTeX file and the funny DT output problem does not happen. I put link to PDF from LaTeX in http:/pj.freefaculty.org/scraps/mre-dt-3.pdf
In your final chunk, knitr sees that you have two objects that its attempting to print and you're getting the output for both. This isn't a feature, and has been addressed in a previous question.
If you want to only print the head of the first object in that chunk, your code should be head(poolballs[, weight2:=2 * weight])

R inline markdown

I’m using R Markdown in RStudio to create a report that mixes Markdown and R output. I know how to use inline R expressions in the Markdown, but I’m wondering how to do the converse, i.e., use Markdown within the R code. I want to loop through a series of calculations and get Markdown headings for each one. I want headings for formatting purposes (e.g., bold titles etc) and also to be able to specify (sub)sections in the resulting PDF (which is a nice feature of the way RMarkdown handles # and ## etc).
I know I can do the following:
---
title: "test"
output: pdf_document
---
#Section 1
```{r, echo=FALSE}
print(1+1)
```
#Section 2
```{r, echo=FALSE}
print(2+2)
```
#Section 3
```{r, echo=FALSE}
print(3+3)
```
Which gives something looking (roughly) like this:
Section 1
## [1] 2
Section 2
## [1] 4
Section 3
## [1] 6
Is it possible to achieve the same output using something along the lines of this:
---
title: "test2"
output: pdf_document
---
```{r, echo=FALSE}
for (i in 1:3)
{
print(paste("#Section",i))
print(i+i)
}
```
As #scoa pointed out, you have to set the chunk option results='asis'. You should also place two \n both before and after your header.
---
title: "test"
output: pdf_document
---
```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
cat(paste0("\n\n# Section", i, "\n\n"))
print(i+i)
cat("\n\n\\newpage")
}
```
As a more general answer, it could be useful to a look at the markdownreports package that parses markdown code (and output) from your R variables.

Resources