In R, character vectors have two pieces of data:
- A sequence of bytes.
- An encoding in which those bytes should be interpreted.
To encode a specific string in R, use the Encoding() function. This Encoding() function is different from encodeString(). Let’s see what is encodeString() and how we can use it.
encodeString in R
To encode the character vector as for printing in R, use the encodeString() method. The encodeString() function escapes the strings in a character vector in the same way print.default does, and optionally fits the encoded strings within a field width.
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.
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.
It returns a character vector of the same length as x, with the same attributes but with no class set.
x <- "ps5\nnvidia\nrestock" print(x) cat("interprets escapes", "\n") cat(x, "\n") cat("After using encodeString", "\n") cat(encodeString(x), "\n", sep = "_")
 "ps5\nnvidia\nrestock" interprets escapes ps5 nvidia restock After using encodeString ps5\nnvidia\nrestock_
There are some characters that 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.
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) 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")
 "outriders" "returnal" "rangnarok"  "outriders" "returnal" "rangnarok"  "outriders" "returnal " "rangnarok"  "outriders" "returnal " "rangnarok"  "outriders" " returnal" "rangnarok"  "'outriders'" " 'returnal'" "'rangnarok'"
That is it for encodeString in R
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.