The R programming language comes with a number of useful built-in functions to work with strings. In this tutorial, we will look at one such function to concatenate two or more strings in R with the help of some examples.
How to concatenate strings in R?

You can use the built-in paste()
function to concatenate two or more strings together in R. Pass the strings you want to concatenate as comma-separated arguments to the paste()
function.
The following is the syntax –
# concatenate strings paste(s1, s2, ..., sep=" ", collapse=NULL)
You can also specify a custom separator to use while concatenating the strings using the sep
parameter which is set to a single space " "
by default.
It returns the concatenated string.
Examples
Let’s now look at some examples of using the above syntax to join strings together in R.
Concatenate two strings with a single space
Pass the two strings as arguments to the paste()
function. Note that the order of the arguments is important as the resulting string will have the same order.
# create two strings s1 = "Marco" s2 = "Polo" # concatenate strings s <- paste(s1, s2) # display the concatenated string print(s)
Output:
[1] "Marco Polo"
You can see that the paste()
function by default joins the strings with a single space character, " "
as the separator.
You can also specify a custom separator using the sep
parameter.
Let’s now join the above two strings using a comma ","
as the separator.
# create two strings s1 = "Marco" s2 = "Polo" # concatenate strings with comma s <- paste(s1, s2, sep=",") # display the concatenated string print(s)
Output:
[1] "Marco,Polo"
The resulting string is joined using the comma character ","
as the separator.
Concatenate more than two strings together
You can use the paste()
function to join more than two strings together. Pass the strings you want to join as comma-separated arguments.
Let’s look at an example.
# create four strings s1 = "You are" s2 = "My fire" s3 = "The one" s4 = "Desire" # concatenate strings with "..." s <- paste(s1, s2, s3, s4, sep="...") # display the concatenated string print(s)
Output:
[1] "You are...My fire...The one...Desire"
Here, we concatenate four strings, s1
, s2
, s3
, and s4
using"..."
as the separator. We get a single concatenated string as the output.
You might also be interested in –
- Convert String to Uppercase in R
- Compare Two Strings in R (With Examples)
- R – Remove Whitespaces From String
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.