1. Collapsing multiple elements into a string
Alright, the "glue" function concatenates strings and variables in a readable way, but what if the data that we work with and that we would like to print in a human readable way is not just one variable but for example a vector?
2. Introducing glue_collapse
That's exactly what "glue collapse" does. Let's first take a look at a simple example. Here we have a vector "usernames" that contains four user names Adam, Betty, Cora and David. When we pass that vector to the glue collapse function it will take all elements of the vector and concatenate them. The result will be one single string with all the user names one after another. What is this useful for, you might ask yourself.
3. More elaborate example
This will get obvious when we look at an example that is a bit more elaborate: Let's call the glue_collapse function again with our vector "usernames" but this time with additional arguments.
The second argument the collapse function takes is "sep", which is short for "separator". The separator is a string that will be put in between the elements of the vector. Here, we'll pass it a comma followed by a space.
The next argument that we pass, is "last". What we pass to it will be a special separator between the last two elements. Very often this is used for the word "and". It will create an enumeration which is very human readable, in our example it now prints "Adam comma Betty comma Cora comma and David".
However, what was just me reading out the last name from memory. As you can see, it actually prints not the whole name but three dots. That is because of the fourth argument that I passed: "width".
Width defines the maximum length of the outputted string. So as soon as the result of the function would exceed 27 characters, it will get cut off and be replaced with three dots.
4. Passing glue collapse to glue
We often will find ourselves in the situation that we want to create a real sentence where we list all elements of a vector. So how do we achieve this? Well, you might already guess the answer to that question based on the last lesson. As we can always pass a string to the glue function, we can also pass it the result of our glue collapse function. The result is a human readable sentence: Hello Adam, Betty, Cora and David.
5. Collapsing columns of a data frame
Luckily the columns of a data frame work just the same way as a vector does. So if we take this very simple data frame "df" with two columns "x" and "y" with some coordinates in it, we can pass the columns to the glue collapse function. To access the column "x" for example, we can write df, dollar sign x. Glue collapse will concatenate all the contents of the column x, so in this case: 123.
6. Let's practice!
Alright, let's create some sentences from our tables!