How to Convert R Vector to String

R stores every character within double quotes, even when you create them with a single quote. The vector in R contains elements of the same type. A “string” is a character variable that includes one or more characters. A character vector is a set of strings stored as the single object.

Let’s see how to cast the vector to string using different approaches.

Convert R Vector to String

To convert vector to string in R, use either paste() function or toString() function. The main difference between vector and string in R is that vector can correctly contain objects while string works only on primitive data types. 

Convert Vector to String using paste() function in R

The paste() method converts its input arguments to character strings and concatenates them. If you want to concate strings in R, use the paste() function. The paste() function concatenates the vectors or strings.

A “string” is just a character variable that contains one or more characters. 

Syntax

paste(x, sep=" ", collapse=NULL)

Parameters

x: It is a vector having values.

sep: It is a character string to separate the terms. Not NA_character_.

collapse: It is an optional character string to separate the results. Not NA_character_.

Use the collapse argument to convert a vector to string.

Example

rv <- c("Ahsoka", "Din", "Grogu")
mando <- paste(rv, collapse = " ")
print(mando)

Output

[1] "Ahsoka Din Grogu"

You can see that we got a string in the output.

Convert Vector to String using toString() function

To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.

Syntax

toString(x, width = NULL)

Parameters

x: It is an R object.

width: It is for the maximum field width. Values of NULL or 0 indicate no maximum. The minimum value allowed is 6, and smaller values are perceived as 6.

Example

rv <- c("Ahsoka", "Din", "Grogu")
mando <- toString(rv)
print(mando)

Output

[1] "Ahsoka, Din, Grogu"

To check the data type of object in R, use the typeof() function.

rv <- c("Ahsoka", "Din", "Grogu")
mando <- toString(rv)
print(typeof(mando))

Output

[1] "character"

That is it for this tutorial.

See also

R vector to list

R vector to data frame

R vector to matrix

Leave a Comment