Programmatically insert text, headers and lists wi

2019-01-18 02:35发布

When using R markdown if one wants to add text using code there are some simple ways to do it.

This is also true for tables, using the kable command is very easy.

However, imagine you want to programmatically insert headers or lists to your report.

```{r, results='asis'}
headers=list("We","are","your","friends")
for (i in list_a){
    #add i as header
}
```

and you want this to be the same as writing in your Rmd file:

#We
#are
#your
#friends

Another example would be to automatically create headers instead of lists:

```{r, results='asis'}
list_a=list("We","are","your","friends")
for (i in list_a){
    #print i to a rmd list
}
```

as before this should have the same result as writing:

*We
*are
*your
*friends

This is not only a formatting problem as the table of context for Rmd files is created dynamically according to these headers.

标签: r markdown
3条回答
狗以群分
2楼-- · 2019-01-18 03:13

Use the pander package, which transform R objects into Pandoc's markdown:

> headers=list("We","are","your","friends")
> list_a=list("We","are","your","friends")
> library(pander)
> pandoc.header(headers)

# We

# are

# your

# friends
> pander(list_a)


  * We
  * are
  * your
  * friends

<!-- end of list -->

The first example used a helper function to create the headers, while the second demo simply called the generic S3 method, that can robustly transform a variety of R objects into markdown.

查看更多
倾城 Initia
3楼-- · 2019-01-18 03:21

For people who want plots below each header, this is how I do it.

```{r, results="asis"}

for (i in headers){
      cat("# ", i, "\n",
          knitr::knit_child("plot.Rmd", quiet = TRUE), "\n")
    }

```

In the plot.Rmd put your plot code in it, e.g.

```{r}
# plotting code
```
查看更多
何必那么认真
4楼-- · 2019-01-18 03:27

You need to construct your wanted markdown in R and use that together with the argument results = 'asis' in your chunk options. Hence, something like the following will do what you want:

```{r, results='asis'}
headers <- list("We","are","your","friends")
for (i in headers){
  cat("#", i, "\n")
}
```

The for-loop here will create the output

# We 
# are 
# your 
# friends 

which is used directly as input in the .md document.

查看更多
登录 后发表回答