R - substring() Function
The R substring() 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 first is larger than the string length then "" is returned.
For the replacement functions, if first 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 substring(x, first, last) #replaces the specified substring #with specified value substring(x, first, last) <- value
Parameters
x |
Required. Specify the string to extract/replace from. |
first |
Required. Specify the first element to be extracted/replaced. Note that the first position in string starts with 1. |
last |
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 substring() function to extract the specified substring.
x1 <- "Hello World!" x2 <- substring(x1, 7, 12) x3 <- substring(x1, 7:12, 7:12) print(x1) print(x2) print(x3) cat("\n") v1 <- c("12345", 12345, "ABCDE", "abcde", "pqrst") v2 <- substring(v1, 2, 4) print(v1) print(v2)
The output of the above code will be:
[1] "Hello World!" [1] "World!" [1] "W" "o" "r" "l" "d" "!" [1] "12345" "12345" "ABCDE" "abcde" "pqrst" [1] "234" "234" "BCD" "bcd" "qrs"
Example: Replaces the specified substring
The substring() function can also be used to replace the specified substring with specified value. Consider the example below:
x1 <- "Hello World!" print(x1) substring(x1, 7, 11) <- "Marry" print(x1) cat("\n") v1 <- c("12345", 12345, "ABCDE", "abcde", "pqrst") print(v1) substring(v1, 2, 4) <- "000" print(v1) substring(v1, 2, 4) <- c("000", "111") 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" [1] "10005" "11115" "A000E" "a111e" "p000t"
❮ R String Functions