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)
)