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" |
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" |
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" |
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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read some of the other tutorials on this website.
- Extract First or Last n Characters from String in R
- Split Character String at Whitespace in R
- Split Character String into Chunks
- strsplit Function in R
- Capitalize First Letter of Each Word in Character String
- Split Data Frame Variable into Multiple Columns
- The R Programming Language
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.
Statistics Globe Newsletter