是否有特定的 R 函数可以最大程度地控制打印字符串的格式?

Is there a specific R function that gives the greatest control over the formatting of printed strings?

考虑字符串 "Hello \n World!"。似乎格式化和打印它的相关方法是print.defaultcat,如果需要,format然后printcat。然而,它们中的每一个似乎都能做一些其他人做不到的事情。是否有任何一种终极打印功能可以最大程度地控制我的字符串的 formatting/printing?

例如,我在 printformatprint.default 的文档中看不到任何地方可以让他们尊重我的 \n 并放一个"Hello \n World!" 中的换行符与 cat 一样,但我也看不到 catprint("Hello \n World!", quote=FALSE) 那样在 "Hello \n World!" 中保留引号.

如果我们还需要引号,请将其用 dQuote 包裹在 cat

cat( dQuote("Hello \n World!", FALSE))
"Hello 
 World!"

根据?cat

Character strings are output ‘as is’ (unlike print.default which escapes non-printable characters and backslash — use encodeString if you want to output encoded strings using cat). Other types of R object should be converted (e.g., by as.character or format) before being passed to cat. That includes factors, which are output as integer vectors.


或者我们可以使用message。优点是它也可以与 RMD 文件一起使用,其中那些 message 将打印在控制台上而不是文档上

message('"Hello \n World!"')
#"Hello 
# World!"

即作为试验,创建一个简单的 RMD 文件

---
output:
  html_document:
    df_print: paged
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)
library(ggplot2)
```


```{r trial 1, echo = FALSE, message = FALSE}
message("data(mtcars) is created with message")
print("data(mtcars) is created with print")
glue::glue("data(mtcars is created with glue")

```

-输出

注意:我们已经指定了 message = FALSE。因此,它不会出现在文档中,而对于调试,它仍然会打印在 Rmarkdown 控制台输出上

...
data(mtcars) is created with message
output file: test1.knit.md
...

这可以使用 Tidyverse 的 glue 来实现。胶水将尊重 \n。您可以通过将字符串包裹在单引号 ' 中或使用 \".

转义来打印双引号
library(glue)

# wrap in single quote
glue('"Hello \n World!"')

# escape the double quotes
glue("\"Hello \n World!\"")

只需修改cat

foo = function(...) {
    s = paste0("\"", ..., "\"")
    cat(s)
}
foo("Hello \n World!")
#"Hello 
# World!"