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

In R, a vector can be converted to a string using the paste(), paste0(), or sprintf() functions. These functions allow the user to specify the character used to separate the elements of the vector as well as the order in which they appear. Additionally, the sprintf() function can be used to add formatting to the vector elements. Examples of how to use each of these functions to convert a vector to a string are provided.


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 <- c("Andy", "Bernard", "Caleb", "Dan", "Eric", "Frank", "Greg")

#convert vector to string
new_string <- paste(x, collapse = " ")

#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 <- c("Andy", "Bernard", "Caleb", "Dan", "Eric", "Frank", "Greg")

#convert vector to string
new_string <- paste(x, collapse = "")

#view string
new_string

[1] "AndyBernardCalebDanEricFrankGreg"

Or we could add a dash between each word:

#create vector
x <- c("Andy", "Bernard", "Caleb", "Dan", "Eric", "Frank", "Greg")

#convert vector to string
new_string <- paste(x, collapse = "-")

#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 <- c("Andy", "Bernard", "Caleb", "Dan", "Eric", "Frank", "Greg")

#convert vector to string
new_string <- toString(x)

#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.

x