Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r markdown - format text in code chunk with new lines

Tags:

Question

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?

Data and example

I would like to parse text <- "this is\nsome\ntext" 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\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  ``` 

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

like image 575
tospig Avatar asked Apr 11 '15 08:04

tospig


People also ask

How do you insert a line break in R Markdown?

To break a line in R Markdown and have it appear in your output, use two trailing spaces and then hit return .

How do I add text in R chunk?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How do I indent text in R Markdown?

Text can be indented two ways depending on if the indent is within a list or not. Within a list, four spaces at the begin of the line indicates the text is to be indented one nesting level. Use four additional spaces for each additional nesting level. To indent text which is not in a list, use a block quote.


1 Answers

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

Example:

```{r, results='asis'} text <- "this is\nsome\ntext"  mycat <- function(text){   cat(gsub(pattern = "\n", replacement = "  \n", 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

like image 98
Rentrop Avatar answered Sep 17 '22 22:09

Rentrop