String Concatenation with Concat
In this lesson, we introduce how the +
operator may be used
in combining strings. 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 Pandas dataframe.
+
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 +
operator. Let's see it in action.
Oh well, why did the output give us "bluemountain" instead of
"blue mountain"? This happened because when we use this function to
combine two strings, it merges them exactly as they are,
without adding any space in between. To include a space,
we must explicitly add it with an additional
+
operator.
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!