Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

r markdown - format text in code chunk with new lines

Question

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

Data and example

I would like to parse text <- "this is some text" to be displayed as:

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
some
text"  # This is the text I would like displayed

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

text                    # same as print

```

Additional Information

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

e.g ui.R

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

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

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

An example of this is here in the R Studio gallery

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Example:

```{r, results='asis'}
text <- "this is
some
text"

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

mycat(text)
```

Result:

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...