以编程方式插入带有R标记的文本,标题和列表 [英] Programmatically insert text, headers and lists with R markdown

查看:66
本文介绍了以编程方式插入带有R标记的文本,标题和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用R markdown时,如果要使用代码添加文本,可以使用一些简单的方法来实现.

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

对于表也是如此,使用kable命令非常简单.

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
}
```

,并且您希望它与在Rmd文件中写入相同:

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

这不仅是格式问题,因为Rmd文件的上下文表是根据这些标头动态创建的.

推荐答案

您需要在R中构造所需的markdown,并将其与块选项中的参数results = 'asis'一起使用.因此,类似以下内容的内容将满足您的需求:

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")
}
```

此处的for循环将创建输出

# We 
# are 
# your 
# friends 

,直接用作.md文档中的输入.

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

这篇关于以编程方式插入带有R标记的文本,标题和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆