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:
- 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:
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.