String Concatenation in R

[This article was first published on R-Chart, 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.

String concatenation is a rather basic function – but my particular programming reflexes did not help me figure out how to do this in R. I tried the + and & operator, and even the || operator to no avail. Also tried concat() function… no dice. The answer?

> paste(‘this string is concatenated’, ‘to this string’)

Not exactly intuitive eh? Even more confusing since R uses a lot of UNIX idioms… and in this case, the paste command (which in UNIX is used to combine files) performs a rather different role. A couple of itmes to note:

  • The two strings above are concatenated with a space between them!
  • Additional strings can be included as arguments:
> paste(‘a’,’b’,’c’)
  • If you use a vector for an argument, you can use the collapse parameter to achieve the same sort of result:
> paste(c(‘a’,’b’,’c’), collapse=’ ‘)
  • As always, more information is available through R’s help system:
> ?paste

I found this exercise fascinating – so many things in R just “work” like I hope they will. Many functions take lists, vectors, or whatever is thrown their way and do the “right” thing with them. There is plenty of C like syntax that is familiar – but there are significant differences that just need to be memorized. String concatenation seems to fit into this category.

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