Nicholas Hamilton
Nicholas Hamilton

Reputation: 10506

Rmarkdown Dynamic Content

I want to use R to produce dynamic content for use in an an Rmd file.

Lets say I have a vector of characters, chars, how can I produce a document paragraph from each item in the vector?

Consider the following:

```{r echo=TRUE}
chars = c("ABC","DEF","GHI")
for(char in chars){ print(char) }
```

The above produce R output, formatted as programming output, but I actually want it as document content, in other words, three paragraphs, containing the strings 'ABC', 'DEF' and 'GHI' respectively

Upvotes: 0

Views: 590

Answers (4)

Nicholas Hamilton
Nicholas Hamilton

Reputation: 10506

This is the solution I ended up using, first create a function:

printSection = function(content){
  if(any(content != '')){
    cat(gsub(pattern = "\n", replacement = "  \n\n", x = paste(content,collapse="\n")))
  }
}

Then use it as follows:

```{r echo=FALSE,result='asis'}
printSection(c("ABC","DEF","GHI"))
```

Upvotes: 0

kabr
kabr

Reputation: 1339

You can combine the previous answers to create more complex HTML.

 ```{r echo=TRUE, results='asis'}

chars = c("ABC","DEF","GHI")   

for(char in chars){


    cat(paste("<div class='div1'><div class='div2'>", char,"</div></div>"), sep = "") 

}

```

If you want to style your div's, just include you style.css in the header:

---
title: ""
author: ""
date: ""
output: 
  html_document:
    css: style.css

---

Upvotes: 0

Elin
Elin

Reputation: 6755

Something like this would work for what you want.

```{r, echo=FALSE}
# Load your libraries here

chars = c("ABC", "DEF", "HIJ")
newstring<-paste(chars, "", collapse = "", sep = "  \n")

```
`r newstring`

Rmarkdown uses two blank spaces at the end of a line to enforce a hard return. But you need to put the new line in your sep to actually make sure that the two spaces are at the end of the line.

Upvotes: 1

lukeA
lukeA

Reputation: 54237

You could do

```{r echo=TRUE, results='asis'}
chars = c("ABC","DEF","GHI")
for(char in chars){ cat('<p>', char, '</p>') }
```

Upvotes: 1

Related Questions