Extract First Entry from Character String Split in R (2 Examples)

 

This tutorial shows how to get the first part of a character string in the R programming language.

Table of contents:

Here’s how to do it:

 

Creation of Exemplifying Data

The following data will be used as basement for this R programming tutorial:

my_string <- "This is a character string"    # Create example character string
my_string                                    # Print example character string
# [1] "This is a character string"

Have a look at the previous output of the RStudio console. It shows that our example data is a character string containing multiple words separated by a space.

 

Example 1: Get First Entry from String Split Using strsplit() & Index Position

Example 1 explains how to use the strsplit function and the index position to extract the first element of a character string after splitting this string.

Consider the following R code:

strsplit(my_string, " ")[[1]][1]             # Extract first element
# [1] "This"

The RStudio console has returned “This” after applying the previous R code, i.e. the first word in our character string.

 

Example 2: Get First Entry from String Split Using sub() Function

In this example, I’ll illustrate how to use the sub function instead of the strsplit function to return the first part of a character string.

For this, we can remove everything after our separator including the separator itself:

sub(" .*", "", my_string)                    # Extract first element
# [1] "This"

As you can see, the output of the previous R syntax is the same as in Example 1. However, this time we have used the sub function instead of the strsplit function.

 

Video & Further Resources

Have a look at the following video on my YouTube channel. In the video, I show the R syntax of this tutorial in RStudio.

 

The YouTube video will be added soon.

 

In addition, you may read some of the other tutorials on this website.

 

To summarize: In this R tutorial you have learned how to extract the leading part after splitting a character string. Let me know in the comments section below, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

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

Menu
Top