substring()
substring(text, first, last = .Machine$integer.max) Returns:
character · Updated March 13, 2026 · String Functions strings substring base
substring() extracts or replaces substrings from character vectors using start and stop positions. It extends substr() with more flexible indexing and can be used on the left-hand side of assignments for in-place modification.
Syntax
substring(text, first, last = .Machine$integer.max)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
text | character | — | A character vector |
first | integer | — | Starting position (1-indexed) |
last | integer | .Machine$integer.max | Ending position (defaults to end of string) |
Examples
Basic usage
x <- "Hello World"
substring(x, 1, 5)
# [1] "Hello"
substring(x, 7)
# [1] "World"
# Using negative indices (from end)
substring(x, -4)
# [1] "World"
Replacing substrings
x <- "Hello World"
substring(x, 1, 5) <- "Hi"
x
# [1] "Hi World"
Working with vectors
words <- c("apple", "banana", "cherry")
substring(words, 2, 4)
# [1] "ppl" "ana" "her"
# From position to end
substring(words, 3)
# [1] "ple" "nana" "erry"
Vectorized first/last arguments
text <- "ABCDEF"
# Different start positions for each element
substring(text, c(1, 2, 3))
# [1] "ABCDEF" "BCDEF" "CDEF"
# Different lengths via last parameter
substring(text, 1, c(2, 4, 6))
# [1] "AB" "ABCD" "ABCDEF"
Common Patterns
Get file extension
filename <- "report.pdf"
ext_start <- nchar(filename) - 2
substring(filename, ext_start)
# [1] "pdf"
Last n characters
text <- "example.txt"
n <- 4
substring(text, nchar(text) - n + 1)
# [1] "e.txt"