StringR – operations on strings

This time we’ll show you some helpful functions from the stringr library that work on strings. Let’s load the library first:

Let’s create a sample vector with company names:

We can use the function str_detect to check wheather a particular phrase/letter occurs in a paricular element of the vector:

Str_which in turn will return us the index of elements containing that phrase:

If we want to count how many times a particular phrase occurs in the elements, we use str_count:

Text fragments can be separated with str_sub:

We select the elements that contain the phrase using str_subset:

And we extract the length of each element with str_length:

Unnecessary spaces at the beginning and end of the string are removed with str_trim:

Replacing phrases in elements with other other phrases with str_replace:

We convert strings to uppercase with str_to_upper:

As in a sentence we will use str_title:

We will combine two strings with str_c:

We convert a vector of strings into a single string with:

We sort the strings with str_sort:

Of course, you can find more functions in the documentation. We encourage you to.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil