How to Concatenate a Vector of Strings in R? (With Examples)

In R, you can use the paste() function to concatenate a vector of strings into a single string. This is done by passing the vector of strings as the first argument to the paste() function, and then setting the sep argument to specify the separator between the strings. Additionally, you can use the collapse argument to specify a final separator between the concatenated strings. Examples include paste(vector, sep=”,”, collapse=” and “) and paste(vector, sep=”/”) to join the strings with a comma and an “and” at the end, or to join the strings with a slash.


You can use one of the following methods in R to concatenate a vector of strings together:

Method 1: Use paste() in  Base R

paste(vector_of_strings, collapse=' ')

Method 2: Use stri_paste() from stringi Package

library(stringi)

stri_paste(vector_of_strings, collapse=' ')

Both methods will produce the same result but the stri_paste() method will be faster, especially if you’re working with extremely large vectors.

The following examples show how to use each method in practice.

Example 1: Concatenate Vector of Strings Using paste() in Base R

The following code shows how to concatenate together a vector of strings using the paste() function from base R:

#create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings
paste(vector_of_strings, collapse=' ')

[1] "This is a vector of strings"

Note that the collapse argument specifies the delimiter to place in between each string.

In the example above, we used a space. However, we could use any delimiter we’d like such as a dash:

#create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings using dash as delimiter
paste(vector_of_strings, collapse='-')

[1] "This-is-a-vector-of-strings"

We can even use no delimiter if we’d like each of the strings to be concatenated with no spaces in between:

#create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings using no delimiter
paste(vector_of_strings, collapse='')

[1] "Thisisavectorofstrings"

Example 2: Concatenate Vector of Strings Using str_paste() from stringi Package

The following code shows how to concatenate together a vector of strings using the stri_paste() function from the stringi package in R:

library(stringi)

#create vector of strings
vector_of_strings <- c('This', 'is', 'a', 'vector', 'of', 'strings')

#concatenate strings
stri_paste(vector_of_strings, collapse=' ')

[1] "This is a vector of strings"

Notice that this produces the same result as the paste() function from base R.

The only difference is that this method will be faster.

Depending on the size of the string vectors you’re working with, the difference in speed may or may not matter to you.

The following tutorials explain how to perform other common operations in R:

x