How to Extract Characters from a String in R
Last Updated :
23 Jul, 2025
Strings are one of R's most commonly used data types, and manipulating them is essential in many data analysis and cleaning tasks. Extracting specific characters or substrings from a string is a crucial operation. In this article, we’ll explore different methods to extract characters from a string in R, including functions like substr(), substring(), and various string manipulation functions from the stringr package.
Basic String Extraction in R
R provides a few built-in functions that allow you to extract specific characters or parts of a string. The two most commonly used functions for this purpose are substr() and substring().
1: Extract Characters from a String Using substr()
The substr() function allows you to extract a substring by specifying the characters' start and end positions.
substr(x, start, stop)
- x: The input string.
- start: The position of the first character to extract.
- stop: The position of the last character to extract.
Lets discuss one example for Extract Characters from a String Using substr().
R
# Example string
string <- "Data Science with R"
# Extract characters from position 6 to 12
substring_part <- substr(string, start = 6, stop = 12)
substring_part
Output:
[1] "Science"
2: Extract Characters from a String Using substring()
The substring() function works similarly to substr(), but it allows you to omit the stop argument, making it easier to extract all characters from a starting position to the end of the string.
substring(text, first, last = nchar(text))
- text: The input string.
- first: The starting position.
- last: (Optional) The ending position. If omitted, it extracts up to the end of the string.
Lets discuss one example for Extract Characters from a String Using substring().
R
# Extract from position 11 to the end
substring_part <- substring(string, first = 11)
substring_part
Output:
[1] "ce with R"
Extracting Characters from Strings with stringr
The stringr package provides a powerful set of functions for string manipulation in R. One advantage of stringr is that it uses a more consistent syntax, making it easier to work with multiple string operations.
To use stringr, you first need to install and load the package:
# Install stringr if not already installed
install.packages("stringr")
# Load the stringr package
library(stringr)
1: Extracting Characters from Strings Using str_sub()
The str_sub() function from the stringr package works like substring() but has a more flexible and intuitive syntax. It allows for both positive and negative indexing, where negative indices count from the end of the string.
str_sub(string, start, end = -1)
- string: The input string.
- start: The starting position.
- end: (Optional) The end position (negative indexing allows counting from the end).
Lets discuss one example for Extracting Characters from Strings Using str_sub().
R
# Example string
string <- "Data Science with R"
# Extract the first 4 characters
str_sub(string, start = 1, end = 4)
# Extract the last 2 characters using negative indexing
str_sub(string, start = -2)
Output:
[1] "Data"
[1] " R"
2: Extracting Specific Parts of a String Using str_extract()
The str_extract() function allows you to extract parts of a string that match a specific pattern using regular expressions.
str_extract(string, pattern)
- string: The input string.
- pattern: The regular expression pattern to match.
Lets discuss one example for Extracting Specific Parts of a String Using str_extract().
R
# Extract the first word
str_extract(string, "\\w+") # Output: "Data"
# Extract a word starting with "S"
str_extract(string, "S\\w+") # Output: "Science"
Output:
[1] "Data"
[1] "Science"
Extracting Multiple Substrings
You can also extract multiple parts of a string or apply string extraction operations to a vector of strings. If you have a vector of strings, you can apply the substr() or str_sub() function across all the strings in the vector.
R
# Vector of strings
strings <- c("Apple", "Banana", "Cherry")
# Extract the first 3 characters from each string
substr(strings, start = 1, stop = 3)
Output:
[1] "App" "Ban" "Che"
Working with Complex Strings
Sometimes, strings can be more complex, such as containing special characters, numbers, or spaces. In such cases, regular expressions and the stringr package functions are especially helpful. Suppose you have a string that contains both letters and numbers, and you want to extract only the numbers:
R
# Example string with numbers
text <- "Order number: 12345"
# Extract the numbers using a regular expression
str_extract(text, "\\d+")
Output:
[1] "12345"
Conclusion
R offers several ways to extract characters and substrings from strings, from simple built-in functions like substr() and substring() to more advanced tools in the stringr package, such as str_sub() and str_extract(). These tools provide flexibility for both simple and complex string manipulation tasks. Whether you're working with a single string or a vector of strings, you now have the knowledge to extract exactly what you need.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is an Operating System? An Operating System is a System software that manages all the resources of the computing device. Acts as an interface between the software and different parts of the computer or the computer hardware. Manages the overall resources and operations of the computer. Controls and monitors the execution o
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read