0
0
R Programmingprogramming~15 mins

sub and gsub in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
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 title
Use gsub to replace all occurrences of "old" with "new" in each title
Print 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
1
Create a vector of book titles
Create a vector called titles with these exact book titles: "The old house", "An old story", "Old and older", "The old old man"
R Programming
Need a hint?

Use the c() function to create a vector of strings.

2
Create a variable for the word to replace
Create a variable called old_word and set it to the string "old"
R Programming
Need a hint?

Just assign the string "old" to the variable old_word.

3
Use sub to replace the first occurrence of "old"
Create a new vector called titles_sub by using sub to replace the first occurrence of old_word with "new" in titles
R Programming
Need a hint?

Use sub(pattern, replacement, x, ignore.case = TRUE) to replace only the first match ignoring case.

4
Use gsub to replace all occurrences of "old" and print results
Create a new vector called titles_gsub by using gsub to replace all occurrences of old_word with "new" in titles. Then print titles_sub and titles_gsub exactly in this order.
R Programming
Need a hint?

Use gsub() like sub() but it replaces all matches. Use print() to show the results.