Search code examples
rr-markdownknitrr-glue

Cancel new line preventions in R's glue package


In the glue package you "can use \\ at the end of a line to prevent adding a newline". In LaTeX \\ is the new line symbol.

I am looking for a better solution than my current one

glue_data(iris,
"\\midrule
\\textbf{{{mean(Petal.Length)}} & 820 &  100\\% \\\\
~other & 902 \\\\"
)

Actual output:

\midrule
\textbf{3.758} & 820 & 100\% \~other & 902 \\

Expected output:

\midrule
\textbf{3.758} & 820 &  100\% \\
~other & 902 \\

My current ugly and error-prone fix:

glue_data(iris,
"\\midrule
\\textbf{{{mean(iris$Petal.Length)}} & 820 &  100\\% \\\\\\
\n~other & 902 \\\\"
)

\midrule
\textbf{3.758} & 820 &  100\% \\
~other & 902 \\

Solution

  • A better method I found was to add the LaTeX linebreaks in as a variable to prevent them from being interpreted by glue:

    lineb <- '\\\\'
    glue_data(
      iris,
      "\\midrule
      \\textbf{{{mean(Petal.Length)}} & 820 &  100\\% {lineb}
      ~other & 902 \\\\"
    )
    

    Output

    \midrule
    \textbf{3.758} & 820 &  100\% \\
    ~other & 902 \\