1

I'm trying to generate some Latex code using R's paste0(). In order to print a percent sign, I need a single backslash in front of it, i.e., the result should be something like $95\%$. However, paste0() will not let me add a single backslash.

  • paste0(95, "%") - Gives "95%", which is of course useless for Latex.
  • paste0(95, "\%") - Will throw Error: '\%' is an unrecognized escape in character string starting ""\%"
  • paste0(95, "\\%") - Will output BOTH backslashes, i.e., "95\\%". But I only want one.

In this post, it says paste0() with \\% will output \%, but that is not the case for me. Any idea what's going on?

I'm using R version 4.2.3 (2023-03-15 ucrt).

EDIT: Solutions using cat() work in the console, but are not displayed in an R Markdown/Quarto document, e.g. when using the following inline code:

`r cat("95\\%")`

Thanks in advance!

  • Look at `cat(paste0(95, "\\%"))`. By default `print()` will escape special characters with slashes. If you use `cat()` you will see the "real" value without any escaping. – MrFlick Apr 06 '23 at 18:55
  • You don't need the `cat` when knitting. That cat just shows you what's "really" there in the console. You need `\`r paste0(95, "\\%")\`` in your latex document. – MrFlick Apr 06 '23 at 19:22
  • Oh dang, I was certain that I had tried that and it didn't work. Now it works just fine - must have been a different mistake before. Seems like I was stupid *shakes head – einGlasRotwein Apr 06 '23 at 19:27

1 Answers1

1

I use glue

library(glue)

glue("95\\%")

95\%

We can also generate the strings dinamically:

value <- 95

glue("{value}\\%")


95\%
GuedesBF
  • 8,409
  • 5
  • 19
  • 37