R Tutorial: Putting strings together

Richard Cotton shows how to concatenate strings in R using paste and writelines. Learn the sep and collapse arguments, vector recycling, and practical examples like formatting pizza orders and creating annotated output.
Chapters
You've seen how to enter strings in R and how to turn numbers into strings. Now you'll learn how to put strings together into more complicated output. Paste takes strings as input and joins them together. Here's a simple example. We pass in five strings, an E, an I, an E, an I, and an o and get a single string as output, where each string has been pasted to the others with a space in between. The sep argument, short for separator, controls the character used between the entries, so we can easily join the strings together with a dash instead by specifying sep as the string that contains a dash. Now we have eieio. Paste gets really useful when you pass in vectors of strings. Every vector that is passed in gets recycled to the length of the longest vector. If you haven't heard of recycling before, it's a common behavior in R where a vector is repeated up to a specified length. Once all the vectors are recycled to the same length, the strings are combined element by element. The easiest way to think about this is the arguments to paste are like the columns in a matrix. The output is a vector of the rows of that matrix. The recycling behavior means the vectors you pass in can all be different lengths, but I recommend you keep them the same length or length one, otherwise it can get pretty confusing. Here's a clue. Can you guess where the examples in this video might be heading? Usually you'll use paste with a mix of fixed strings and variables, allowing you to build up complicated output. The other argument to paste is collapse. When specified, it further collapses all the resulting strings into one with the specified character between them. If we specify collapse to be the string containing a comma and a space, we get a single string as a result. By combining multiple paste commands, you can get pretty complicated output. As an example, here's my old Mac function that takes two arguments and with paste and writelines will keep you singing Old MacDonald Has a Farm. As long as you can keep coming up with new animals. Of course, paste can be used to put together more than just nursery rhymes. You'll use paste to annotate numbers, output a simple table, and create some pizza orders in the following exercises.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







