Using sub and gsub in R to Replace Text
📖 Scenario: You work in a small publishing company. You have a list of book titles, but some titles have the word "old" that you want to update or remove.
🎯 Goal: You will learn how to use sub and gsub functions in R to replace text in strings. You will replace only the first occurrence of "old" in each title with "new" and then replace all occurrences of "old" with "new".
📋 What You'll Learn
Create a vector of book titles with some titles containing the word "old" multiple times
Create a variable to hold the word to replace: "old"
Use
sub to replace only the first occurrence of "old" with "new" in each titleUse
gsub to replace all occurrences of "old" with "new" in each titlePrint the results after each replacement
💡 Why This Matters
🌍 Real World
Replacing text in strings is common when cleaning data, updating documents, or preparing text for reports.
💼 Career
Knowing how to use <code>sub</code> and <code>gsub</code> helps data analysts and programmers clean and transform text data efficiently.
Progress0 / 4 steps