Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
```
like image 424
Russell.Hobbs Avatar asked Aug 04 '15 14:08

Russell.Hobbs


People also ask

How do I add an inline code in R Markdown?

Code results can be inserted directly into the text of a . Rmd file by enclosing the code with `r ` . The file below uses `r ` twice to call colorFunc , which returns “heat.

How do I add an inline code in r?

A code chunk usually starts with ```{} and ends with ``` . You can write any number of lines of code in it. Inline R code is embedded in the narratives of the document using the syntax `r ` .

What does inline mean in r?

Inline code enables you to insert R code into your document to dynamically updated portions of your text. To insert inline code you need to encompass your R code within: . For example, you could write: Which would render to: The mean sepal length found in the iris data set is 5.8433333.

What is inline code?

Inline code refers to any lines of code that are added in the body of a program. It can be any type of code written in any programming language. The inline code executes independently and is usually executed under some condition by the primary program.


1 Answers

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")
}
```
like image 84
Christoph Avatar answered Nov 01 '22 15:11

Christoph