Home > database >  RMarkdown PDF add non-spacing linebreak inside paste0()
RMarkdown PDF add non-spacing linebreak inside paste0()

Time:01-18

I want to use RMarkdown to combine several sentences in the paste0-function, and insert a non-spacing line break in between.
In pure Markdown, a simple backslash \ is sufficient to generate a non-spacing line break. However, this does not work in the character string of the paste0-function.
I have already inserted \n\n between the sentences. However, there is a space between the lines, which I want to avoid.

Can anyone help me with my problem?
The programmatic scheme with the code chunk and the subsequent inline code should be the same.

Here is my example code:

---
title: "Untitled"
output: pdf_document
date: "2023-01-17"
---

```{r echo=FALSE}
result_1 <- 100
result_2 <- 200
```

```{r echo=FALSE}
final_text <- paste0("My first result is ", result_1, "My second result is ", result_2)
```

`r final_text`

The first and second sentences are the result of the \n\n-separator.
The third and fourth sentences are my desired outcome (created with a \ in plain Markdown) enter image description here

CodePudding user response:

The result of putting `r final_text` into your text will be the same as if the characters in the final_text variable were inserted there. So you just need to insert the characters that resulted in the output you want. If those characters are

My first result is 100\
My second result is 200

then you can get that output using this R code:

---
title: "Untitled"
output: pdf_document
date: "2023-01-17"
---

```{r echo=FALSE}
result_1 <- 100
result_2 <- 200
```

```{r echo=FALSE}
final_text <- paste0("My first result is ", result_1, "\\\nMy second result is ", result_2)
```

`r final_text`

The explanation for the string \\\n at the start of the second line is as follows: Use \\ to get a single backslash, then use \n to get a line break.

  • Related