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.