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"

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges