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

Viewed 74

Consider the string "Hello \n World!". It appears that the relevant methods for formatting and printing it are print.default, cat, and if need be, format then print or cat. However, each of these seem to be able to do some things that the others cannot. Is there any one ultimate printing function that gives the maximum amount of control over the formatting/printing of my strings?

For example, I can't see anywhere in print, format, or print.default's documentations that would make them respect my \n and put a line break in "Hello \n World!", as cat does, but I also can't see anyway to make cat keep the quotation marks in "Hello \n World!", as print("Hello \n World!", quote=FALSE) would.

3 Answers

If we need the quotes as well, wrap it with dQuote within cat

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

According to ?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.


Or we can use message. The advantage is that it can be used as well with RMD files where those messages will be printed on the console rather than on the document

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

i.e. as a trial, create a simple RMD file

---
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")

```

-output

enter image description here

NOTE: We already specified message = FALSE. So, it would not show up in the document, whereas for debugging, it still prints on the Rmarkdown console output

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

This is possible using glue from Tidyverse. glue will respect the \n. And you can print the double quotes by wrapping the string in a single quotes ' or escaping them with \".

library(glue)

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

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

Just modify the cat

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