How to Concatenate Strings in R

To concatenate strings in R, you can use the paste() function to take multiple strings as an input, combine them, and return a concatenated string as an output. The syntax is paste(…, sep = “”, collapse = NULL), where are the strings to be concatenated, sep is the separator to be inserted between each string, and collapse is the separator to be inserted between each row if the input is a matrix or a data frame.

Example 1: How to use paste() function to concatenate string

# R program to concatenate two strings

str_1 <- "Jenna"
str_2 <- "Ortega!"

# concatenate two strings using paste function
concatenated_string <- paste(str_1, str_2)

print(concatenated_string)

Output

[1] "Jenna Ortega!"

The paste() function in R can concatenate two or more strings together. In our program, we first defined two strings, str_1 and str_2.

In the next step, we used the paste() function to concatenate the two strings together and store the result in a new variable concatenated_string.

Example 2: Concatenate Strings in R with No Separator

To concatenate strings in R with no separator, you can use the paste() function with an empty string as the sep argument, or you can use the paste0() function, which is equivalent to paste() with a zero-length separator.

str_1 <- "Jenna"
str_2 <- "Ortega!"

# concatenate two strings using paste function
concatenated_string <- paste(str_1, str_2, sep = "")
print(concatenated_string)

# concatenate the two strings with no separator using paste0()
res2 <- paste0(str_1, str_2)

# view result
res2

Output

[1] "JennaOrtega!"
[1] "JennaOrtega!"

Example 3: Concatenate Multiple Strings in R

To concatenate multiple strings in R, you can use the paste() function, which can take multiple strings as input, combine them, and returns a concatenated string.

str_1 <- "Jenna"
str_2 <- "Ortega"
str_3 <- "Millie"
str_4 <- "Brown"

output <- paste(str_1, str_2, str_3, str_4)
output

with_sep <- paste(str_1, str_2, str_3, str_4, sep = ",")
with_sep

Output

[1] "Jenna Ortega Millie Brown"
[1] "Jenna,Ortega,Millie,Brown"

Using the cat() function to concat the string in R

The cat() function in R concatenates objects and prints them to the console or a file. The syntax is a cat(…, file = “”, sep = ” “, append = FALSE), where are the objects to be concatenated, the file is the file name to send output to, the sep is the separator to use between objects, and the append is whether to append output to an existing file or overwrite it.

str_1 <- "Jenna"
str_2 <- "Ortega"
str_3 <- "Millie"
str_4 <- "Brown"

cat(str_1, str_2, str_3, str_4, sep = "\n")

Output

Jenna
Ortega
Millie
Brown

That’s it for the concatenation of strings in R.

Leave a Comment