R Program to Concatenate a Vector of Strings

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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"
To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)