R – Concatenate Strings

In this tutorial, we will learn how to Concatenate Strings in R programming Language.

To concatenate strings in r programming, use paste() function.

The syntax of paste() function that is used to concatenate two or more strings.

paste(…, sep="", collapse=NULL)

where

pasteis the keyword
input strings separated by comma. Any number of strings can be given.
sepis a character that would be appended between two adjacent strings and acts as a separator
collapseis an optional character to separate the results

While concatenating strings in R, we can choose the separator and number number of input strings. Following examples demonstrate different scenarios while concatenating strings in R using paste() function.

Example 1 – Concatenate Strings in R

In this example, we will use paste() function with default separator, and concatenate two strings.

r_strings_concatenate_two.R

# Example R program to concatenate two strings

str1 = 'Hello'
str2 = 'World!'

# concatenate two strings using paste function
result = paste(str1,str2)

print (result)

Output

$ Rscript r_strings_concatenate_two.R 
[1] "Hello World!"

The default separator in paste function is space " ". So ‘Hello’ and ‘World!’ are joined with space in between them.

ADVERTISEMENT

Example 2 – Concatenate Strings in R with No Separator

In this example, we shall use paste() function with the no separator given as argument. If no value is passed as argument for sep, the default value of empty string is considered.

r_strings_concatenate_two.R

# Example R program to concatenate two strings

str1 = 'Hello'
str2 = 'World!'

# concatenate two strings using paste function
result = paste(str1,str2,sep="")

print (result)

Output

$ Rscript r_strings_concatenate_two.R 
[1] "HelloWorld!"

Please observe that we have overwritten default separator in paste function with “”. So ‘Hello’ and ‘World!’ are joined with nothing in between them.

Example 3 – Concatenate Multiple Strings

In this example, we shall use paste() function with the separator as hyphen, i.e., sep="-" and also we take multiple strings at once.

r_strings_concatenate_multiple.R

# Example R program to concatenate two strings

str1 = 'Hello'
str2 = 'World!'
str3 = 'Join'
str4 = 'Me!'

# concatenate two strings using paste function
result = paste(str1,str2,str3,str4,sep="-")

print (result)

Output

$ Rscript r_strings_concatenate_multiple.R 
[1] "Hello-World!-Join-Me!"

You may provide as many strings as required followed by the separator to the R paste() function to concatenate.

Conclusion

In this R Tutorial, we have learned to concatenate two or more strings using paste() function with the help of example programs.