How to Append or Concatenate String in R

To append or concat a string in R, use the paste() function. The paste() is a built-in function that concatenates or appends two or more strings with an optional separator.

Syntax

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

Arguments

The is an R object.

The sep is a character string to separate the terms.

The default value of collapse is NULL. It is an optional character string to separate the results.

Example

Append one string to another using the paste() function.

str1 <- "Millie"
str2 <- "Bobby Brown"

# append a string to a string using paste() function
mbb <- paste(str1, str2)

print(mbb)

Output

[1] "Millie Bobby Brown"

The default separator in this example is space(” “). Here, we appended one string to another with space in between them.

The first string is “Millie”, and the second is “Bobby Brown”. Using the paste() function, we appended the second string to the first string and got the output: “Millie Bobby Brown”.

How to append multiple strings in R

To append multiple strings in R, use the paste() function. The paste() function takes multiple strings as arguments and returns one string, which is a concatenated string.

Example

str1 <- "Albus"
str2 <- "Percival"
str3 <- "Wolfric"
str4 <- "Brian"
str5 <- "Dumbledore"

# append a string to a string using paste() function
headmaster <- paste(str1, str2, str3, str4, str5, sep = " ")
print(headmaster)

Output

[1] "Albus Percival Wolfric Brian Dumbledore"

Using the paste() function, we appended multiple strings into one. The paste() function can append any number of strings into one string.

That’s it.

Leave a Comment