r markdown-用新行格式化代码块中的文本 [英] r markdown - format text in code chunk with new lines

查看:324
本文介绍了r markdown-用新行格式化代码块中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

在R Markdown(.Rmd)文档中的代码块中,如何解析包含换行字符\n的字符串,以在换行上显示文本?

Within a code chunk in an R Markdown (.Rmd) document how do you parse a string containing new line characters \n, to display the text on new lines?

数据和示例

我想将text <- "this is\nsome\ntext"解析为:

this is
some
text 

这是一个示例代码块,它尝试了几次(不会产生所需的输出):

Here is an example code chunk with a few attempts (that don't produce the desired output):

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

text <- "this is\nsome\ntext"  # This is the text I would like displayed

cat(text, sep="\n")     # combines all to one line
print(text)             # ignores everything after the first \n
text                    # same as print

```

其他信息

文本将来自闪亮应用程序上的用户输入.

The text will come from a user input on a shiny app.

例如 ui.R

tags$textarea(name="txt_comment")      ## comment box for user input

然后我有一个download按钮,该按钮使用.Rmd文档来呈现输入:

I then have a download button that uses a .Rmd document to render the input:

```{r, echo=FALSE, results='asis'}
input$txt_comment
```

R Studio画廊中的示例在这里

An example of this is here in the R Studio gallery

推荐答案

诀窍是在"\n"之前连续使用两个空格: 因此,将"\n"替换为" \n"

The trick is to use two spaces before the "\n" in a row: So replace "\n" by " \n"

示例:

```{r, results='asis'}
text <- "this is\nsome\ntext"

mycat <- function(text){
  cat(gsub(pattern = "\n", replacement = "  \n", x = text))
}

mycat(text)
```

结果:

P.S .:这与SO(正常降价行为)相同
如果只想换行,请在要换行的末尾使用两个空格

P.S.: This is the same here on SO (normal markdown behaviour)
If you want just a linebreak use two spaces at the end of the line you want to break

这篇关于r markdown-用新行格式化代码块中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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