R inline markdown - r

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.

Related

How to extract all code from an RMarkdown (.Rmd) file?

How can I extract all the code (chunks) from an RMarkdown (.Rmd) file and dump them into a plain R script?
Basically I wanted to do the complementary operation described in this question, which uses chunk options to pull out just the text (i.e. non-code) portion of the Rmd.
So concretely I would want to go from an Rmd file like the following
---
title: "My RMarkdown Report"
author: "John Appleseed"
date: "19/02/2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents.
For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
Some text description here.
```{r cars}
a = 1
print(a)
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Some more comments here.
To an R script containing just the code portions of the above, as the following:
knitr::opts_chunk$set(echo = TRUE)
a = 1
print(a)
summary(cars)
plot(pressure)
You could use knitr::purl, see convert Markdown to R script :
knitr::purl(input = "Report.Rmd", output = "Report.R",documentation = 0)
gives Report.R:
knitr::opts_chunk$set(echo = TRUE)
a = 1
print(a)
summary(cars)
plot(pressure)
Another way is to set the purl hook in your Rmd:
```{r setup, include=FALSE}
knitr::knit_hooks$set(purl = knitr::hook_purl)
knitr::opts_chunk$set(echo = TRUE)
```
Then the R script is generated when you knit. You can exclude some chunks with the chunk option purl = FALSE.

Looping Flextables in R Markdown documents with Word output

I am looking to print multiple flextables in a single R Markdown document. This is not challenging when using html output, but I need Word output.
With html output, the following R Markdown code (example taken from https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents) produces a document with multiple Flextables:
---
output:
html_document: default
---
```{r}
library(htmltools)
library(flextable)
ft <- flextable(head(iris))
tab_list <- list()
for(i in 1:3){
tab_list[[i]] <- tagList(
tags$h6(paste0("iteration ", i)),
htmltools_value(ft)
)
}
tagList(tab_list)
```
I have been unable to get an equivalent output using Word document output.
The solution proposed in
How to knit_print flextable with loop in a rmd file similarly works fine with html output, but I have failed to get this to render correctly with Word output.
Any advice on a R Markdown Word document output equivalent of the above example would be very helpful!
You need to use flextable::docx_value and the chunk option results='asis'
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r results='asis'}
ft <- flextable(head(iris))
for(i in 1:3){
cat("<w:p/>")## add this to add an empty new paragraph between tables
flextable::docx_value(ft)
}
```

How to generate rmarkdown chunk within a chunk

I'm trying to generate a rmarkdown chunk using code. I've read similar questions and their solutions, such as using pander or using cat. I just can't seem to generate it. I also tried knitting the output manually. Here's an example of a Rmd file:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
"2+2",
"```")
pander::pander(txt)
```
When I knit this, I get a verbatim {r} 2+2. I would like to see the number four instead. In my real example, I'm using bookdown and trying to generate a block2 chunk.
Any ideas how to generate this chunk that gets evaluated as R code?
Does this do what you want?
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
2+2,
"```")
pander::pander(txt)
```
This evalutates to
```{r} 4 ```
in your markdown document.
You using a string literal "2+2" as opposed to the expression 2+2. This is the first issue, I guess.
If you want it correctly parsed you need to add an sep = "\n" argument to paste or manually add the newline breaks.
I.e.
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}\n",
2+2,
"\n```", sep = "")
pander::pander(txt)
```
This evalutates to
```{r}
4
```
which is interpreted as R code in the markdown document.

R, list all packages and versions used in a markdown file

Hi I'm using R and R studio. Is there a way I can have my R markdown file list all the packages and their respected versions at the end of the documents? thanks! For example,
---
title: "test"
output: pdf_document
---
## R Markdown
```{r cars}
library(ggplot2)
library(gplots)
summary(cars)
```
You can get the names of loaded non-base packages with names(sessionInfo()$otherPkgs), so maybe something like this:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r}
library(ggplot2)
library(data.table)
summary(cars)
```
```{r}
installed.packages()[names(sessionInfo()$otherPkgs), "Version"]
```

How to include external R file with RMarkdown? [duplicate]

It's fairly trivial to load external R scripts as per this R Sweave example:
<<external-code, cache=FALSE>>=
read_chunk('foo-bar.R')
#
Can the same be done for R Markdown?
Yes.
Put this at the top of your R Markdown file:
```{r setup, echo=FALSE}
opts_chunk$set(echo = FALSE, cache=FALSE)
read_chunk('../src/your_code.R')
```
Delimit your code with the following hints for knitr (just like #yihui does in the example):
## #knitr part1
plot(c(1,2,3),c(1,2,3))
## #knitr part2
plot(c(1,2,3),c(1,2,3))
In your R Markdown file, you can now have the snippets evaluated in-line:
Title
=====
Foo bar baz...
```{r part1}
```
More foo...
```{r part2}
```

Resources