Solution Review: Append Hearts
Explore solutions to append repeated heart strings in R programming. Learn to create functions that use rep and replicate to duplicate characters across vectors and practice applying these techniques to advanced vector manipulation challenges.
We'll cover the following...
We'll cover the following...
Solution #1: Using rep()
Explanation
In the code snippet above, we first create a function:
hearts <- function(testVariable)
In this function, we define the string heart <- "<3"
that we need to replicate. Then initiate a loop over all the elements of the vector testVariable, that is passed to the function. Using the function:
rep(heart, i)
we duplicate the heart string i times.
Solution #2: Using replicate()
Explanation
We can also use the function replicate() to solve this problem.
replicate(i, heart)
# Here i is the number of times the string needs to be duplicated and heart is the string being replicated.
In the next lesson, we have another challenge for you to conquer.