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


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.

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

Leave a Reply

Your email address will not be published.