在`paste0()`函数中如何获得百分号(%)?

huangapple go评论70阅读模式
英文:

How to get \% in paste0()?

问题

以下是翻译的部分:

我正在尝试使用R的paste0()生成一些Latex代码。为了打印百分号,我需要在它前面加一个单反斜杠,即结果应该类似于$95\%$。然而,paste0()不允许我添加一个单反斜杠。

  • paste0(95, "%") - 得到"95%",这对Latex来说当然是无用的。
  • paste0(95, "\%") - 会引发错误:Error: '\%' is an unrecognized escape in character string starting ""\%"
  • paste0(95, "\\%") - 会输出两个反斜杠,即"95\\%"。但我只想要一个

这篇帖子中提到,使用\\%paste0()会输出\%,但对我来说并非如此。有什么想法?

我正在使用R版本4.2.3(2023-03-15 ucrt)。

编辑:在控制台中使用cat()的解决方法有效,但在R Markdown/Quarto文档中不会显示,例如在使用以下内联代码时:

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

提前感谢!

英文:

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!

答案1

得分: 1

I use glue

library(glue)

glue("95\\%")

95\%

We can also generate the strings dinamically:

value <- 95

glue("{value}\\%")

95\%
英文:

I use glue

library(glue)

glue("95\\%")

95\%

We can also generate the strings dinamically:

value <- 95

glue("{value}\\%")


95\%

</details>



huangapple
  • 本文由 发表于 2023年4月7日 02:54:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定