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.
paste(x, sep=" ", collapse=NULL)
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.
rv <- c("Ahsoka", "Din", "Grogu") mando <- paste(rv, collapse = " ") print(mando)
 "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.
toString(x, width = NULL)
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.
rv <- c("Ahsoka", "Din", "Grogu") mando <- toString(rv) print(mando)
 "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))
That is it for this tutorial.
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.