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

How to Concatenate Strings in R (With Examples)

by Tutor Aspire

You can use the paste() function in R to quickly concatenate multiple strings together:

paste(string1, string2, string3 , sep = " ")

The following examples show how to use this function in practice.

Example 1: Concatenate String Vectors

Suppose we have the following strings in R:

#create three string variables
a 

We can use the paste() function to quickly concatenate these three strings into one string:

#concatenate the three strings into one string
d #view result
d

[1] "hey there friend"

The three strings have been concatenated into one string, separated by spaces.

We can also use a different value for the separator by supplying a different value to the sep argument:

#concatenate the three strings into one string, separated by dashes
d 

Example 2: Concatenate String Columns in Data Frame

Suppose we have the following data frame in R:

#create data frame
df frame(first=c('Andy', 'Bob', 'Carl', 'Doug'),
                 last=c('Smith', 'Miller', 'Johnson', 'Rogers'),
                 points=c(99, 90, 86, 88))

#view data frame
df

  first    last points
1  Andy   Smith     99
2   Bob  Miller     90
3  Carl Johnson     86
4  Doug  Rogers     88

We can use the paste() function to concatenate the “first” and “last” columns into a new column called “name”:

#concatenate 'first' and 'last' name columns into one column
df$name = paste(df$first, df$last)

#view updated data frame
df

  first    last points         name
1  Andy   Smith     99   Andy Smith
2   Bob  Miller     90   Bob Miller
3  Carl Johnson     86 Carl Johnson
4  Doug  Rogers     88  Doug Rogers

Notice that the strings in the “first” and “last” columns have been concatenated in the “name” column.

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