Stop pasting, start gluing
The function paste()
concatenates strings with a space in between, so paste("Hi", "there")
will output "Hi there"
. There is also the paste0()
function that doesn't add a space, the result of which would be "Hithere"
. But when you concatenate multiple strings and variables, you end up writing a lot of double quotes "
and commas ,
and with code that is not very readable. Plus you can only work with variables that are already present.
These are the two use cases where the glue()
function really shines. You can either work with variables that are available in the global scope or you can create variables on the fly. In this exercise, you'll see the difference between paste()
and glue()
in action.
This is a part of the course
“Intermediate Regular Expressions in R”
Exercise instructions
- Recreate the sentence that was created with
paste0()
usingglue()
. - Create a temporary variable
n
which stores the length of characters infirstname
and pass it sentence being created.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
firstname <- "John"
lastname <- "Doe"
paste0(firstname, "'s last name is ", lastname, ".")
# Create the same result as the paste above with glue
glue("___'s last name is ___.")
# Create a temporary varible "n" and use it inside glue
glue(
"The name {firstname} consists of ___ characters.",
___ = nchar(firstname)
)
This exercise is part of the course
Intermediate Regular Expressions in R
Manipulate text data, analyze it and more by mastering regular expressions and string distances in R.
In this chapter, we will slightly move away from regular expressions and focus on string manipulation by creating strings from other data structures like vectors or lists.
Exercise 1: Getting to know glueExercise 2: Stop pasting, start gluingExercise 3: Gluing data framesExercise 4: How many arguments can glue take?Exercise 5: Collapsing multiple elements into a stringExercise 6: Formulating a question from a listExercise 7: Collapsing data framesExercise 8: Glue and Collapse, what's the difference?Exercise 9: Gluing regular expressionsExercise 10: Construct "or patterns" with glueExercise 11: Using the "or pattern" with a larger datasetExercise 12: Make advanced patterns more readableWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.