How to Extract Substrings in R

04.21.2021

String modification is a common task in R. One of those tasks is extracting a substring from a string. In this article, we will learn how to extract substrings in R.

To extract substrings, we can use the substring method. The function has the following form substr(string, start, end). Here we can pass in the string we would like to extract and the start and end positions of the substring.

substr("Hello, World", 1, 5)
#> [1] "Hello"

R is also supportive of vector operations. We can use the substr method to extract substrings from a vector of strings.

months = c("January", "February", "March")
substr(months, 1, 3)
#> [1] "Jan" "Feb" "Mar"