R substr() Function - Extract and Replace Substrings
R substr() function is used to extract or replace substrings at specified positions from a string.
substring() is an alias of substr(), with basically the same behavior.
The syntax of the substr() function is as follows:
substr(x, start, stop) substring(text, first, last = 1000000L)
Parameter description:
x/textInput string or string vector.
start/firstStarting position (starting from 1).
stop/lastEnding position.
Example
text <- "Hello EXAMPLE"
# Extract characters 2 to 5
result1 <- substr(text, 2, 5)
print(result1)
# Extract substrings from a vector
words <- c("apple", "banana", "cherry")
result2 <- substr(words, 1, 3)
print(result2)
# Replace substrings
str <- "Hello EXAMPLE"
substr(str, 7, 12) <- "WORLD"
print(str)
# Extract characters 2 to 5
result1 <- substr(text, 2, 5)
print(result1)
# Extract substrings from a vector
words <- c("apple", "banana", "cherry")
result2 <- substr(words, 1, 3)
print(result2)
# Replace substrings
str <- "Hello EXAMPLE"
substr(str, 7, 12) <- "WORLD"
print(str)
Executing the above code produces the following output:
[1] "ello" [1] "app" "ban" "che" [1] "Hello WORLD"
substr() is commonly used to extract encoded information in fixed formats:
Example
# Extract the birth year from ID card number (characters 7-10)
id_numbers <- c("110101199001011234", "310105198505067890")
birth_years <- substr(id_numbers, 7, 10)
print(paste(Birth year:, birth_years))
id_numbers <- c("110101199001011234", "310105198505067890")
birth_years <- substr(id_numbers, 7, 10)
print(paste(Birth year:, birth_years))
Executing the above code produces the following output:
[1] "出生年份: 1990" "出生年份: 1985"Other Extensions
R Language Examples