Reverse Character String in R (2 Examples)

 

In this article you’ll learn how to change the order of characters in a string in the R programming language.

Table of contents:

Let’s get started!

 

Creation of Example Data

At first, we have to create some data that we can use in the exemplifying syntax below:

x <- c("ABCDE", "XYZ", "AAABBB")          # Create vector of strings
x                                         # Print vector of strings
# [1] "ABCDE"  "XYZ"    "AAABBB"

Have a look at the previous output of the RStudio console. It shows that our example data is a vector of character strings containing three elements.

 

Example 1: Reverse Character String Using Base R

In this section, I’ll explain how to reverse the ordering of the characters in our vector of strings using the basic installation of the R programming language.

For this, we have to use the sapply, lapply, strsplit, and rev functions as shown below:

sapply(lapply(strsplit(x, NULL), rev),    # Reverse strings using Base R
       paste,
       collapse = "")
# [1] "EDCBA"  "ZYX"    "BBBAAA"

The previous console output shows our updated vector. As you can see, we have changed the order of the characters in each string.

 

Example 2: Reverse Character String Using stringi Package

The R programming code of Example 1 has been relatively complicated. For that reason, I’ll demonstrate how to easily reverse a character string using the stringi package in R.

We first need to install and load the stringi package:

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

Next, we can apply the stri_reverse function of the stringi package as shown below:

stri_reverse(x)                           # Reverse strings using stringi package
# [1] "EDCBA"  "ZYX"    "BBBAAA"

The previous output is exactly the same as in Example 1. However, this time the R syntax was much less complex.

 

Video, Further Resources & Summary

Some time ago I have released a video on my YouTube channel, which demonstrates the R programming codes of this tutorial. You can find the video below:

 

 

Furthermore, you might have a look at some of the related tutorials on this website:

 

To summarize: In this R tutorial you have learned how to reverse the order of characters in a string. In case you have additional questions or comments, let me know in the comments. Furthermore, don’t forget to subscribe to my email newsletter for updates on the newest tutorials.

 

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.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top