题
在R Markdown(.Rmd)文档的代码块中,如何解析包含换行符的字符串\n,以在新行上显示文本?
数据和示例
我想解析text <- "this is\nsome\ntext"显示为:
this is
some
text
Run Code Online (Sandbox Code Playgroud)
这是一个示例代码块,只有几次尝试(不产生所需的输出):
```{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
```
Run Code Online (Sandbox Code Playgroud)
附加信息
该文本将来自闪亮应用程序上的用户输入.
例如,ui.R
tags$textarea(name="txt_comment") ## comment box for user input
Run Code Online (Sandbox Code Playgroud)
然后我有一个download使用.Rmd文档来呈现输入的按钮:
```{r, echo=FALSE, results='asis'}
input$txt_comment
```
Run Code Online (Sandbox Code Playgroud)
Ren*_*rop 22
诀窍是"\n"在连续之前使用两个空格:所以替换"\n"为" \n"
例:
```{r, results='asis'}
text <- "this is\nsome\ntext"
mycat <- function(text){
cat(gsub(pattern = "\n", replacement = " \n", x = text))
}
mycat(text)
```
Run Code Online (Sandbox Code Playgroud)
结果:

PS:这在SO上是相同的(正常降价行为)
如果你只想要一个换行符,你想要在行的末尾使用两个空格