0
0
R Programmingprogramming~20 mins

sub and gsub in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sub and Gsub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A"orange apple apple"
B"orange orange orange"
C"apple apple orange"
D"apple orange apple"
Attempts:
2 left
💡 Hint
Remember that sub() replaces only the first match.
Predict Output
intermediate
2: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)
A"cat bat rat"
B"cog bog rog"
C"cog bat rat"
D"cat bog rat"
Attempts:
2 left
💡 Hint
gsub() replaces all matches in the string.
🔧 Debug
advanced
2: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)
ABecause sub() requires the pattern to be a regular expression object
BBecause sub() only replaces the first word in the string
CBecause sub() is case-sensitive and "world" does not match "World"
DBecause the replacement string "Earth" is invalid
Attempts:
2 left
💡 Hint
Check the capitalization of the pattern and the text.
📝 Syntax
advanced
2: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)
Agsub("dog", "cat", text)
Bsub("dog", "cat", text)
C)txet ,"tac" ,"god"(busg
Dgsub("dog", cat, text)
Attempts:
2 left
💡 Hint
Check if the replacement argument is a string or a variable.
🧠 Conceptual
expert
3: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?
Asub() result length: 8, gsub() result length: 8
Bsub() result length: 7, gsub() result length: 7
Csub() result length: 8, gsub() result length: 4
Dsub() result length: 7, gsub() result length: 8
Attempts:
2 left
💡 Hint
Replacing characters with another single character keeps string length the same.