String Concatenation with Paste
In this lesson, we introduce two convenient functions for combining
strings: paste
and paste0
. While the concepts
behind these functions are straightforward, we've chosen to explore
them at this stage in the course to demonstrate their utility in
conjunction with a Tidyverse function.
Paste
Imagine we have two variables, a and b, storing the strings
"blue" and "mountain," respectively. Our goal is to merge these strings
into a single phrase, "blue mountain". This can be achieved effortlessly
using the paste
function. Let's see it in action.
Paste0
We can do the same thing using paste0
. This function
differs from the previous in that there will be no space separated
between the two variables, as such we would see the string
bluemountain instead of blue mountain. As such
we need to add a space in between the two variables.
Two applications
A practical application of these functions is merging strings
with variables to create a new string. In the next code editor
we will embed a number into a string. To convert the
number datatype to a string datatype we use the
as.character
function. For a review
on datatypes, feel free to review the
Datatypes lesson.
Next, let's see an application of paste0
with the iris dataset.
The only string variable we have is Species
, let's append
-flower after every species string and give this new column the name
Flower.
Okay that's it for this short lesson, next on to the exciting world of loops!