String Formatting in R Programming Language

R offers several options for string formatting. Here are some examples of common string formatting tasks.

# Define a custom structure (list in R)
point <- list(x = 1, y = 2)

# Basic printing of a list
cat(sprintf("struct1: %s\n", toString(point)))

# Print list with names
cat(sprintf("struct2: %s\n", paste(names(point), unlist(point), sep = ":", collapse = " ")))

# Print list in a more R-like syntax
cat(sprintf("struct3: %s\n", deparse(point)))

# Print the type of an object
cat(sprintf("type: %s\n", class(point)))

# Formatting booleans
cat(sprintf("bool: %s\n", TRUE))

# Formatting integers
cat(sprintf("int: %d\n", 123))

# Print binary representation
cat(sprintf("bin: %s\n", paste0(as.integer(intToBits(14)), collapse = "")))

# Print character corresponding to an integer
cat(sprintf("char: %s\n", intToUtf8(33)))

# Hexadecimal encoding
cat(sprintf("hex: %x\n", 456))

# Formatting floats
cat(sprintf("float1: %f\n", 78.9))

# Scientific notation
cat(sprintf("float2: %e\n", 123400000.0))
cat(sprintf("float3: %E\n", 123400000.0))

# Basic string printing
cat(sprintf("str1: %s\n", '"string"'))

# Quoting strings
cat(sprintf('str2: "%s"\n', '"string"'))

# Hexadecimal representation of a string
cat(sprintf("str3: %s\n", paste(charToRaw("hex this"), collapse = "")))

# Print memory address (not directly supported in R)
cat(sprintf("pointer: %s\n", "Not directly supported in R"))

# Controlling width of integers
cat(sprintf("width1: |%6d|%6d|\n", 12, 345))

# Controlling width and precision of floats
cat(sprintf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45))

# Left-justifying floats
cat(sprintf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45))

# Controlling width of strings
cat(sprintf("width4: |%6s|%6s|\n", "foo", "b"))

# Left-justifying strings
cat(sprintf("width5: |%-6s|%-6s|\n", "foo", "b"))

# Using sprintf to format and return a string
s <- sprintf("sprintf: a %s", "string")
cat(s, "\n")

# Writing to stderr (similar to Fprintf in Go)
cat("io: an error\n", file = stderr())

To run this R script, save it as string_formatting.R and use:

$ Rscript string_formatting.R

This will output:

struct1: list(x = 1, y = 2)
struct2: x:1 y:2
struct3: list(x = 1, y = 2)
type: list
bool: TRUE
int: 123
bin: 00000000000000000000000000001110
char: !
hex: 1c8
float1: 78.900000
float2: 1.234000e+08
float3: 1.234000E+08
str1: "string"
str2: ""string""
str3: 6865782074686973
pointer: Not directly supported in R
width1: |    12|   345|
width2: |  1.20|  3.45|
width3: |1.20  |3.45  |
width4: |   foo|     b|
width5: |foo   |b     |
sprintf: a string 
io: an error

R’s sprintf function provides similar functionality to Go’s fmt.Printf. The cat function is used here to print the formatted strings. Note that R doesn’t have direct equivalents for all of Go’s formatting verbs, so some adaptations were made.