gpt4 book ai didi

r markdown - 用新行格式化代码块中的文本

转载 作者:行者123 更新时间:2023-12-03 23:26:11 26 4
gpt4 key购买 nike

问题

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

数据和示例

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

this is
some
text

这是一个示例代码块,经过几次尝试(不会产生所需的输出):
```{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

```

附加信息

文本将来自 Shiny 应用程序上的用户输入。

例如 ui.R
tags$textarea(name="txt_comment")      ## comment box for user input

然后我有一个 download使用 .Rmd 的按钮呈现输入的文档:
```{r, echo=FALSE, results='asis'}
input$txt_comment
```

一个 example of this is here在 R Studio 画廊中

最佳答案

诀窍是在 "\n" 之前使用两个空格。连续:
所以替换 "\n"通过 " \n"
例子:

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

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

mycat(text)
```

结果:

enter image description here

P.S.:这在 SO 上是一样的(正常的 Markdown 行为)
如果您只想换行,请在要换行的行尾使用两个空格

关于r markdown - 用新行格式化代码块中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29575768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com