R encodeString() Function

The encodeString() function in R is used to encode character strings in various ways, particularly for ensuring correct alignment and handling of special characters.


encodeString(x, width = 0, quote = "", na.encode = TRUE,
             justify = c("left", "right", "centre", "none"))


  1. x: It is a character vector or an object coerced to one by as.character.
  2. width: It is an integer: the minimum field width. If NULL or NA, this is the largest field width needed for any element of x.
  3. quote: It is a character: quoting character, if any.
  4. na.encode: It is a logical argument: should NA strings be encoded?
  5. justify: It is a character: partial matches are allowed. If padding to the minimum field width is needed, how should spaces be inserted? justify == “none” is equivalent to width = 0, for consistency with format.default.

Return Value

It returns a character vector of the same length as x, with the same attributes but no class set.

Common uses

  1. It can be used when formatting text for output, such as in plot labels or printed tables.
  2. It can also manage special characters, like quotes or escape sequences, in strings.
  3. Create neatly formatted tables for console output.

Example 1: Basic usage

How to use encodeString() function

x <- "ps5\nnvidia\nrestock"

cat("interprets escapes", "\n")
cat(x, "\n")

cat("After using encodeString", "\n")
cat(encodeString(x), "\n", sep = "_")


[1] "ps5\nnvidia\nrestock"
interprets escapes
After using encodeString

Example 2: Using with Vector

Use encodeString() function with Vector

rv <- c("outriders", "returnal", "rangnarok")

encodeString(rv, 2)
encodeString(rv, width = NA)
encodeString(rv, width = NA, justify = "c")
encodeString(rv, width = NA, justify = "r")
encodeString(rv, width = NA, quote = "'", justify = "r")


[1] "outriders" "returnal" "rangnarok"
[1] "outriders" "returnal" "rangnarok"
[1] "outriders" "returnal " "rangnarok"
[1] "outriders" "returnal " "rangnarok"
[1] "outriders" " returnal" "rangnarok"
[1] "'outriders'" " 'returnal'" "'rangnarok'"

That’s it!

Leave a Comment