Home » How to Convert a Vector to String in R (With Examples)

How to Convert a Vector to String in R (With Examples)

by Tutor Aspire

There are two basic ways to convert a vector to a string in R:

Method 1: Use paste()

paste(vector_name, collapse = " ")

Method 2: Use toString()

toString(vector_name)

The following examples show how to use each of these methods in practice.

Method 1: Convert Vector to String Using paste()

The following code shows how to use the paste() function to convert a vector to a string:

#create vector
x #convert vector to string
new_string #view string
new_string

[1] "Andy Bernard Caleb Dan Eric Frank Greg"

You can use the collapse argument to specify the delimiter between each word in the vector. For example, we could remove the space between the words entirely:

#create vector
x #convert vector to string
new_string #view string
new_string

[1] "AndyBernardCalebDanEricFrankGreg"

Or we could add a dash between each word:

#create vector
x #convert vector to string
new_string #view string
new_string

[1] "Andy-Bernard-Caleb-Dan-Eric-Frank-Greg"

Method 2: Convert Vector to String Using toString()

The following code shows how to use the toString() function to convert a vector to a string:

#create vector
x #convert vector to string
new_string #view string
new_string

[1] "Andy, Bernard, Caleb, Dan, Eric, Frank, Greg"

Note that the toString() function always adds commas in between each element in the vector. Thus, you should only use this function if you want commas between each element.

Additional Resources

How to Convert a String to Datetime in R
How to Replace NAs with Strings in R
How to Drop Rows that Contain a Specific String in R

You may also like