From the course: R for Data Science: Lunch Break Lessons

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

sub, gsub, regex, and backreferences

sub, gsub, regex, and backreferences

- [Instructor] With R, you can work with strings. And there are times when you'll want to replace one string with another and for that we have sub and gsub. Let me show you how this works. First, I've created a vector called someText that just contains two lines of poetry. Let's do some substitutions. First of all I'll use sub, S-U-B, and I want to search for the character a and I'd like to replace the character a with a dash and the string that I'm going to search through is someText. When I hit Return, you'll notice that the first line which was Twas brillig in the slithey toves is now Tw-a brillig and the slithey toves and the second line you'll notice that and has also been substituted out as -nd. One thing to note is that there is another a in each line. But the second a was not replaced. If you want to replace all of the characters, you use gsub, it stands for global sub which is gsub and I'm going to search for all of the as. I'm going to replace all of the as with a dash and…

Contents