Bird
Raised Fist0
R Programmingprogramming~10 mins

sub and gsub in R Programming - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - sub and gsub
Input String
↓
Apply Pattern Match
↓
sub: Replace first match only
→Output String
↓
gsub: Replace all matches
→Output String
The flow shows how sub replaces only the first pattern match in a string, while gsub replaces all matches.
Execution Sample
R Programming
text <- "apple apple apple"
sub("apple", "orange", text)
gsub("apple", "orange", text)
Replace 'apple' with 'orange' once using sub, and all occurrences using gsub.
Execution Table
StepFunctionInput StringPatternReplacementResult
1sub"apple apple apple""apple""orange""orange apple apple"
2gsub"apple apple apple""apple""orange""orange orange orange"
💡 Both functions finish after replacing matches; sub replaces only the first, gsub replaces all.
Variable Tracker
VariableStartAfter subAfter gsub
text"apple apple apple""apple apple apple""apple apple apple"
result_subNA"orange apple apple"NA
result_gsubNANA"orange orange orange"
Key Moments - 2 Insights
Why does sub only replace the first 'apple' and not the others?
sub stops after the first match and replaces it, as shown in execution_table row 1 where only the first 'apple' changes.
Does gsub change the original string variable?
No, gsub returns a new string with all replacements; the original 'text' variable remains unchanged as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of sub at step 1?
A"orange apple apple"
B"apple orange apple"
C"orange orange orange"
D"apple apple apple"
💡 Hint
Check the 'Result' column in execution_table row 1.
At which step does the function replace all occurrences of 'apple'?
AStep 1
BStep 2
CNeither step
DBoth steps
💡 Hint
Look at the 'Function' and 'Result' columns in execution_table.
If we assign the result of gsub to 'text', what will variable_tracker show after gsub?
A"apple apple apple"
B"orange apple apple"
C"orange orange orange"
DNA
💡 Hint
Refer to variable_tracker row for 'result_gsub' and imagine assigning it back to 'text'.
Concept Snapshot
sub(pattern, replacement, x) replaces only the first match in x.
gsub(pattern, replacement, x) replaces all matches in x.
Both return a new string; original string stays unchanged unless reassigned.
Use sub for single replacement, gsub for global replacement.
Full Transcript
In R, sub and gsub are functions to replace text patterns in strings. sub replaces only the first occurrence of the pattern, while gsub replaces all occurrences. For example, given the string 'apple apple apple', sub("apple", "orange", text) changes only the first 'apple' to 'orange', resulting in 'orange apple apple'. gsub("apple", "orange", text) changes all 'apple' words to 'orange', resulting in 'orange orange orange'. Neither function changes the original string unless you assign the result back to the variable. This visual trace shows each step and how variables change, helping beginners understand the difference clearly.

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

  1. Step 1: Understand sub behavior

    sub replaces only the first occurrence of the pattern in the string.
  2. Step 2: Understand gsub behavior

    gsub replaces all occurrences of the pattern in the string.
  3. Final Answer:

    sub replaces only the first match, gsub replaces all matches. -> Option C
  4. 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

  1. Step 1: Identify correct function and parameters

    sub takes pattern, replacement, and the string in that order.
  2. Step 2: Check the parameters match the question

    We want to replace "cat" with "dog" in "cat and cat" using sub.
  3. Final Answer:

    sub("cat", "dog", "cat and cat") -> Option A
  4. 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

  1. Step 1: Understand sub replaces first match only

    The first "apple" in the string is replaced by "orange".
  2. Step 2: Apply replacement to the string

    Result becomes "orange apple apple" because only the first "apple" changes.
  3. Final Answer:

    "orange apple apple" -> Option B
  4. 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

  1. Step 1: Identify function behavior

    sub replaces only the first match, so only the first space is replaced.
  2. Step 2: Suggest correct function for all replacements

    To replace all spaces, gsub should be used instead of sub.
  3. Final Answer:

    sub replaces only the first space, use gsub to replace all spaces. -> Option D
  4. 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

  1. Step 1: Identify pattern to remove digits

    The pattern "[0-9]" matches any single digit; "\\d+" matches one or more digits.
  2. Step 2: Choose function to replace all digits

    Use gsub to replace all digit occurrences, not just the first.
  3. Step 3: Check options

    gsub("[0-9]", "", c("cat123", "dog456", "bird789")) uses gsub with "[0-9]" which removes all digits correctly.
  4. Final Answer:

    gsub("[0-9]", "", c("cat123", "dog456", "bird789")) -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard