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.
Cet exercice fait partie du cours
Intermediate Regular Expressions in R
Instructions
- Recreate the sentence that was created with
paste0()usingglue(). - Create a temporary variable
nwhich stores the length of characters infirstnameand pass it sentence being created.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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)
)