R Program to Concatenate a Vector of Strings

Example 1: Concatenate a Vector of Strings Using cat() in R

# create a vector with string values
vector1 <- c("Data Science", "is", "fun")
 
# using cat() to concatenate a vector strings
cat(vector1)

Output

Data Science is fun

In the above example, we have used the cat() function to concatenate the vector named vector1 which contains multiple strings.

So the vector elements "Data Science" "is" "fun" are joined together and Data Science is fun is returned.


Example 2: Concatenate a Vector of Strings Using paste() in R

# create a vector of strings
vector1 <- c("Science", "is","fun")
 
# using paste() and separate vector strings with whitespace
result1 <- paste(vector1, collapse = " ")
 
print(result1)

# using paste() and separate vector strings with hyphen
result2 <- paste(vector1, collapse = "-")
 
print(result2)

Output

[1] "Science is fun"
[1] "Science-is-fun"

Here,

  • paste(vector1, collapse = " " - joins vector of strings with " " as separator of strings. So the output will be "Science is fun"
  • paste(vector1, collapse = "-" - joins vector of strings with "-" as separator of strings. So the output will be "Science-is-fun"