String Concatenation in R

May 10, 2010
By

(This article was first published on R-Chart, and kindly contributed to R-bloggers)

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 his blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags:

Comments are closed.