如何在RMarkdown的paste0函数中插入无间距换行生成PDF?
paste0() Got it, I totally get your frustration—getting line breaks without extra spacing inside paste0() for RMarkdown PDF output can be tricky when regular Markdown tricks don't work. Let's walk through the solutions here.
The core issue is that when generating dynamic text with paste0(), the plain Markdown backslash line break doesn't translate, and \n\n adds unwanted blank lines between sentences. Here are two reliable fixes:
1. Use Markdown's Native Hard Line Break (Works for All Output Types)
Markdown’s standard way to create a line break without extra spacing is to add two spaces followed by a newline. In your paste0() call, you can insert this as a string literal: " \n".
Here's your updated code:
result_1 <- 100 result_2 <- 200
final_text <- paste0("My first result is ", result_1, " \n", "My second result is ", result_2)
r final_text
This will render exactly like the plain Markdown hard break you want—no extra spacing between lines—and it works seamlessly for both PDF and HTML outputs.
2. Use LaTeX Line Break (PDF-Only Solution)
Since you’re targeting pdf_document, you can use LaTeX’s built-in line break command \\. In R strings, backslashes need to be escaped, so you’ll write this as "\\\\" (four backslashes total) to produce a single \\ in the LaTeX output.
Here's the adjusted code for PDF:
result_1 <- 100 result_2 <- 200
final_text <- paste0("My first result is ", result_1, "\\\\", "My second result is ", result_2)
r final_text
This tells LaTeX to break the line immediately without adding a blank space between your two sentences.
Either method will give you the tight, no-space line breaks you’re aiming for. I’d recommend the first approach if you might ever switch to HTML output later, since it’s Markdown-standard and more flexible.
内容的提问来源于stack exchange,提问作者TobKel

