R append to string: How to append string in R

R does not have a string built-in data type but any value written within a pair of single quotes or double quotes is considered as a string. You can format strings to a specific style using the format() function.

R append to string

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

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

We will 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 we got the output: “Millie Bobby Brown”.

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.

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, as you can see in this example.

That’s it for this tutorial.

Leave a Comment