R Tutorial R Charts & Graphs R Statistics R References

R - substr() Function



The R substr() function is used to extract or replace a substring from a character vector. The syntax for using this function is given below:

When extracting, if start is larger than the string length then "" is returned.

For the replacement functions, if start is larger than the string length then no replacement is done. If the portion to be replaced is longer than the replacement string, then only the portion the length of the string is replaced.

Syntax

#extracts the specified substring
substr(x, start, stop)

#replaces the specified substring 
#with specified value
substr(x, start, stop) <- value

Parameters

x Required. Specify the string to extract/replace from.
start Required. Specify the first element to be extracted/replaced. Note that the first position in string starts with 1.
stop Required. Specify the last element to be extracted/replaced.
value Required. Specify the character vector to be replaced with.

Return Value

Returns the extracted character vector.

Example: Extracts substring

The example below shows how to use the substr() function to extract the specified substring.

x1 <- "Hello World!"
x2 <- substr(x1, 7, 12)
print(x1)
print(x2)

cat("\n")

v1 <- c("12345", 12345, "ABCDE", "abcde", "pqrst")
v2 <- substr(v1, 2, 4)
print(v1)
print(v2)

The output of the above code will be:

[1] "Hello World!"
[1] "World!"

[1] "12345" "12345" "ABCDE" "abcde" "pqrst"
[1] "234" "234" "BCD" "bcd" "qrs"

Example: Replaces the specified substring

The substr() function can also be used to replace the specified substring with specified value. Consider the example below:

x1 <- "Hello World!"
print(x1)
substr(x1, 7, 11) <- "Marry"
print(x1)

cat("\n")

v1 <- c("12345", 12345, "ABCDE", "abcde", "pqrst")
print(v1)
substr(v1, 2, 4) <- "000"
print(v1)

The output of the above code will be:

[1] "Hello World!"
[1] "Hello Marry!"

[1] "12345" "12345" "ABCDE" "abcde" "pqrst"
[1] "10005" "10005" "A000E" "a000e" "p000t"

❮ R String Functions