Home » How to Concatenate Vector of Strings in R (With Examples)

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

by Tutor Aspire

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

Additional Resources

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

How to Convert a Vector to String in R
How to Convert Strings to Lowercase in R
How to Perform Partial String Matching in R

You may also like