str_order & str_sort Functions in R (2 Examples)

 

In this article you’ll learn how to order or sort a character vector with the str_order and str_sort functions in the R programming language.

The table of content is structured as follows:

So now the part you have been waiting for – the examples.

 

Creation of Example Data

First, we need to create some example data that we can order and sort later on:

x <- c("xyz", "a", "hello", "y")    # Create vector of characters

In order to use the str_order and str_sort functions, we also need to install and load the stringr package of the tidyverse to R:

install.packages("stringr")         # Install stringr package
library("stringr")                  # Load stringr package

Now, we can move on to the example, so keep on reading!

 

Example 1: Application of str_order Function in R

In the first example, we’ll apply the str_order command. Have a look at the following R syntax:

str_order(x)                        # Apply str_order function
# 2 3 1 4

As you can see, the str_order function returns the alphabetic ordering of our vector of character strings.

 

Example 2: Application of str_sort Function in R

Similar to Example 1, we can also apply the str_sort to sort our vector of character strings:

str_sort(x)                         # Apply str_sort function
# "a"     "hello" "xyz"   "y"

 

Video & Further Resources

I have recently released a video on my YouTube channel, which explains the content of this article. Please find the video below.

 

The YouTube video will be added soon.

 

In addition, you may want to read the related posts that I have published on this website. I have released numerous articles already.

Especially, I need to emphasize the article on the sort and order functions of Base R.

Further interesting articles can be found here:

 

In this tutorial, I explained how to order or sort a vector of character strings in the R programming language. In case you have further comments or questions, don’t hesitate to let me know in the comments.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top