Remove Numbers from Character String in R (Example)
In this tutorial, I’ll illustrate how to extract only the letters from an alphanumeric character string in R programming.
Table of contents:
Let’s take a look at some R codes in action…
Example Data
We’ll use the following data as a basis for this R tutorial.
my_alphanum <- "aa11b2c33" # Create alphanumeric character string my_alphanum # Print string # [1] "aa11b2c33" |
my_alphanum <- "aa11b2c33" # Create alphanumeric character string my_alphanum # Print string # [1] "aa11b2c33"
The previously shown output of the RStudio console shows the structure of our exemplifying data – A single character string containing numbers and letters.
Example: Remove Numbers from Alphanumeric Character String Using gsub() Function
This example shows how to select only the letters from a character string.
To accomplish this, we can apply the gsub function as shown in the following R code:
my_alpha <- gsub("[[:digit:]]", "", my_alphanum) # Extract letters my_alpha # Print letters # [1] "aabc" |
my_alpha <- gsub("[[:digit:]]", "", my_alphanum) # Extract letters my_alpha # Print letters # [1] "aabc"
The previous syntax has returned the character string “aabc”, i.e. only the letters of our input character string.
Video, Further Resources & Summary
In case you need more information on the R code of this page, I recommend watching the following video that I have published on my YouTube channel. In the video, I demonstrate the examples of this article.
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 might read the other tutorials on https://www.statisticsglobe.com/.
- Remove Newline from Character String in R
- Extract Numbers from Character String Vector in R
- Remove All White Space from Character String
- Remove Parentheses in Character String in R
- R Programming Overview
This tutorial has illustrated how to keep only the letters of a character string in R programming. Tell me about it in the comments section below, in case you have any additional questions.
Statistics Globe Newsletter