Challenge - 5 Problems
Sub and Gsub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of sub() with repeated pattern
What is the output of this R code snippet?
R Programming
text <- "apple apple apple" result <- sub("apple", "orange", text) print(result)
Attempts:
2 left
💡 Hint
Remember that sub() replaces only the first match.
✗ Incorrect
The sub() function replaces only the first occurrence of the pattern. So only the first "apple" becomes "orange".
❓ Predict Output
intermediate2:00remaining
Output of gsub() with multiple replacements
What will this R code print?
R Programming
text <- "cat bat rat" result <- gsub("at", "og", text) print(result)
Attempts:
2 left
💡 Hint
gsub() replaces all matches in the string.
✗ Incorrect
The gsub() function replaces all occurrences of the pattern. Here, "at" in each word is replaced by "og".
🔧 Debug
advanced2:00remaining
Why does this sub() call not replace anything?
Consider this R code:
text <- "Hello World"
result <- sub("world", "Earth", text)
print(result)
Why does the output remain "Hello World"?
R Programming
text <- "Hello World" result <- sub("world", "Earth", text) print(result)
Attempts:
2 left
💡 Hint
Check the capitalization of the pattern and the text.
✗ Incorrect
The sub() function is case-sensitive by default. The pattern "world" does not match "World" because of the capital W.
📝 Syntax
advanced2:00remaining
Identify the syntax error in this gsub() usage
Which option contains a syntax error when trying to replace "dog" with "cat" in the string "dog dog dog"?
R Programming
text <- "dog dog dog"
result <- gsub(pattern, replacement, text)Attempts:
2 left
💡 Hint
Check if the replacement argument is a string or a variable.
✗ Incorrect
Option D uses cat without quotes, which is treated as a variable or function, causing an error if undefined.
🧠 Conceptual
expert3:00remaining
Difference in output length between sub() and gsub()
Given the string
"a1b2c3d4", what is the length of the string after applying sub("[0-9]", "X", text) and gsub("[0-9]", "X", text) respectively?Attempts:
2 left
💡 Hint
Replacing characters with another single character keeps string length the same.
✗ Incorrect
Both sub() and gsub() replace digits with "X" without changing string length. So both results have length 8.