📖 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
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
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
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
Hint
Use gsub() like sub() but it replaces all matches. Use print() to show the results.
Practice
(1/5)
1. What is the main difference between sub and gsub in R?
easy
A. sub works only with numbers, gsub works only with text.
B. sub replaces all matches, gsub replaces only the first match.
C. sub replaces only the first match, gsub replaces all matches.
D. sub modifies the original string, gsub returns a new string.
Solution
Step 1: Understand sub behavior
sub replaces only the first occurrence of the pattern in the string.
Step 2: Understand gsub behavior
gsub replaces all occurrences of the pattern in the string.
Final Answer:
sub replaces only the first match, gsub replaces all matches. -> Option C
Quick Check:
sub = first match, gsub = all matches [OK]
Hint: Remember: sub = first, gsub = global (all) [OK]
Common Mistakes:
Confusing which function replaces all matches
Thinking sub modifies original string in place
Assuming gsub only replaces first match
2. Which of the following is the correct syntax to replace the first occurrence of "cat" with "dog" in the string "cat and cat" using sub?
easy
A. sub("cat", "dog", "cat and cat")
B. sub("dog", "cat", "cat and cat")
C. gsub("cat", "dog", "cat and cat")
D. replace("cat", "dog", "cat and cat")
Solution
Step 1: Identify correct function and parameters
sub takes pattern, replacement, and the string in that order.
Step 2: Check the parameters match the question
We want to replace "cat" with "dog" in "cat and cat" using sub.
Final Answer:
sub("cat", "dog", "cat and cat") -> Option A
Quick Check:
Correct syntax with sub and parameters [OK]
Hint: sub(pattern, replacement, string) is the order [OK]
Common Mistakes:
Swapping pattern and replacement arguments
Using gsub instead of sub for first occurrence
Using a non-existent function like replace
3. What will be the output of the following R code?
text <- "apple apple apple"
result <- sub("apple", "orange", text)
print(result)
medium
A. "orange orange orange"
B. "orange apple apple"
C. "apple orange apple"
D. "apple apple orange"
Solution
Step 1: Understand sub replaces first match only
The first "apple" in the string is replaced by "orange".
Step 2: Apply replacement to the string
Result becomes "orange apple apple" because only the first "apple" changes.
Final Answer:
"orange apple apple" -> Option B
Quick Check:
sub replaces first match only [OK]
Hint: sub changes only first match, not all [OK]
Common Mistakes:
Thinking sub replaces all matches
Confusing sub with gsub
Expecting all words to change
4. The following code is intended to replace all spaces with underscores in the string "hello world example" but does not work as expected. What is the error?
text <- "hello world example"
new_text <- sub(" ", "_", text)
print(new_text)
medium
A. The print statement is incorrect syntax.
B. The pattern " " is invalid, use "\\s" instead.
C. The replacement string should be "-" not "_".
D. sub replaces only the first space, use gsub to replace all spaces.
Solution
Step 1: Identify function behavior
sub replaces only the first match, so only the first space is replaced.
Step 2: Suggest correct function for all replacements
To replace all spaces, gsub should be used instead of sub.
Final Answer:
sub replaces only the first space, use gsub to replace all spaces. -> Option D
Quick Check:
Use gsub for all matches, sub for first only [OK]
Hint: Use gsub to replace all matches, not sub [OK]
Common Mistakes:
Using sub when gsub is needed
Thinking space pattern is invalid
Changing replacement character unnecessarily
5. You have a vector of strings: c("cat123", "dog456", "bird789"). You want to remove all digits from each string. Which R code correctly does this using gsub?
hard
A. gsub("[0-9]", "", c("cat123", "dog456", "bird789"))
B. sub("[0-9]", "", c("cat123", "dog456", "bird789"))
C. gsub("[^0-9]+", "", c("cat123", "dog456", "bird789"))
D. sub("\\d", "", c("cat123", "dog456", "bird789"))
Solution
Step 1: Identify pattern to remove digits
The pattern "[0-9]" matches any single digit; "\\d+" matches one or more digits.
Step 2: Choose function to replace all digits
Use gsub to replace all digit occurrences, not just the first.
Step 3: Check options
gsub("[0-9]", "", c("cat123", "dog456", "bird789")) uses gsub with "[0-9]" which removes all digits correctly.
Final Answer:
gsub("[0-9]", "", c("cat123", "dog456", "bird789")) -> Option A
Quick Check:
gsub + digit pattern removes all digits [OK]
Hint: Use gsub with digit pattern to remove all digits [OK]
Common Mistakes:
Using sub instead of gsub, removing only first digit
Incorrect regex pattern for digits
Confusing escape sequences in regex
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.