What is encodeString() Function in R

The encodeString() is a built-in R function that escapes the strings in a character vector like print.default does and optionally fits the encoded strings within a field width.

To encode the character vector for printing in R, you can use the encodeString() method.


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


x: It is a character vector or an object coerced to one by as.character.

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.

quote: It is a character: quoting character if any.

na.encode: It is a logical argument: should NA strings be encoded?

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.

Example 1: How to use encodeString() in R

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

Some characters are non-printable. For example, escapes backslash and the control characters \a (bell), \b (backspace), \f (formfeed), \n (line feed), \r (carriage return), \t (tab), and \v (vertical tab) as well as any non-printable characters in a single-byte locale.

Example 2: Applying encodeString() on Vector in R

To apply the encodeString() function to a vector, see the following code.

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 is it for encodeString in R.

Leave a Comment