The glue_collapse() function is another powerful tool from the glue package. In this post, we will look at practical ways to use this function.
Collapsing Text
As you can probably tell from the name, the glue_collapse() function is useful for collapsing a string. In the code below, we will create an object containing several names and use glue_collapse to collapse the values into one string.
> library(glue)
> many_people<-c("Mike","Bob","James","Sam")
> glue_collapse(many_people)
MikeBobJamesSam
In the code above we called the glue package. Next, we created an object called “many_people” which contains several names separated by commas. Lastly, we called the glue_collapse() function which removes the quotes and commas from the string.
Separate & Last
Another great tool of the glue_collapse() function is the ability to separate strings and have a specific last argument. This technique helps to make the output highly readable. Below is the code
> glue_collapse(many_people,sep = ", ", last = ", and ")
Mike, Bob, James, and Sam
In the code above we separate each string with a comma followed by a space in the “sep” argument. The “last” argument tells R what to do before the last word in the string. In this example, we have a comma followed by a space and the word and.
Collapse a Dataframe
The glue_collapse() function can also be used with data frames. In the example, below we will take a column from a dataframe and collapse it.
> head(iris$Species)
[1] setosa setosa setosa setosa setosa setosa
Levels: setosa versicolor virginica
> glue_collapse(iris$Species)
setosasetosasetosasetosasetosasetosaseto.....
In the code above, we first take a look at the “Species” column from the “iris” dataset using the head() function. Next, we use the glue_collapse() function in the “Species” column. YOu can see how the rows are all collapsed into one long string in this example.
glue and glue_collapse working together
You can also use the glue() and glue_collapse function together as a team.
> glue(
+ "Hi {more_people}.",
+ more_people = glue_collapse(
+ many_people,sep = ", ",last = ", and "
+ )
+ )
Hi Mike, Bob, James, and Sam.
This code is a little bit more complicated but here is what happened.
- On the outside, we start with the glue() function in the first line.
- Inside the glue() function we create a string that contains the word Hi and a temporary variable called “more_people”.
- Next, we define the temporary variable “more_people with the help of the glue_collapse() function.
- Inside the glue_collapse() function we separate the strings inside the “many_people” object.
As you can see, the use of the glue_collapse() and glue() functions can be endless.
Conclusion
The glue_collapse() function is another useful tool that can be used with text data. Knowing what options are available for data analysis makes the process much easier.
