0
0
R Programmingprogramming~5 mins

sub and gsub in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the sub() function do in R?

sub() replaces the first occurrence of a pattern in a string with a replacement.

Click to reveal answer
beginner
How is gsub() different from sub()?

gsub() replaces all occurrences of a pattern in a string, while sub() replaces only the first.

Click to reveal answer
beginner
Example: What is the output of sub("a", "X", "banana")?

The output is "bXnana" because only the first 'a' is replaced by 'X'.

Click to reveal answer
beginner
Example: What is the output of gsub("a", "X", "banana")?

The output is "bXnXnX" because all 'a's are replaced by 'X'.

Click to reveal answer
intermediate
Can sub() and gsub() work with regular expressions?

Yes, both functions use regular expressions to find patterns in strings for replacement.

Click to reveal answer
What does sub("cat", "dog", "catapult") return?
A"dogapult"
B"catapult"
C"dogdog"
D"catdog"
Which function replaces all matches of a pattern in a string?
Asub()
Bgsub()
Cpaste()
Dstrsplit()
What will gsub("[aeiou]", "*", "hello world") output?
A"h*ll* w*rld"
B"hello world"
C"h*llo world"
D"*e*o *o*l*"
If you want to replace only the first space in a string, which function do you use?
Agsub()
Bstr_replace_all()
Csub()
Dpaste()
What is the role of regular expressions in sub() and gsub()?
AThey convert strings to numbers
BThey replace the string directly
CThey split the string
DThey define the pattern to find in the string
Explain the difference between sub() and gsub() in R.
Think about how many replacements each function makes.
You got /3 concepts.
    Describe a real-life example where you would use gsub() instead of sub().
    Imagine editing a whole paragraph, not just one word.
    You got /3 concepts.