substr
Extract or Replace Portions of Character Strings

Description

Returns or replaces a vector of character strings that are substrings of the input.

Usage

substr(x, start, stop)
substr(x, start, stop) <- value
substring(text, first, last = 1000000L)
substring(text, first, last = 1000000L) <- value

Arguments

x a vector of character strings.
start a numeric vector giving the position within each element of x to be the first character in the respective substring.
stop a numeric vector giving the position within each element of x to be the last character in the respective substring.
text the same as x.
first the same as start.
last the same as stop.
value the replacement text.

Details

Characters within each string are numbered from 1 to nchar(string). If start (or first) is larger than the length of a string, the returned string is "".
stop (or last) can go beyond the end of the string, but only the characters from start (or first) to the end of string are returned.
A substring of characters within a string can be changed with `substr<-`. This does not change the number of characters in modified string. Instead, the number of characters changed is the minimum of the length specified by first and last, and the length of the corresponding string element of value. `substring<-` is the same as `substr<-`, except for the argument names.
Value
for substr, a character vector as long as x containing the specified portions of each character string. Any shorter vector of start and stop is replicated.
for substring, a character vector as long as the longest of text, first and last, containing the specified portions of each character string. Any shorter vector is replicated.
See Also
nchar, paste, abbreviate, regexpr.
Examples
substr(c("Illinois", "Indiana", "Iowa"), 1, 5)
# [1] "Illin" "India" "Iowa"

substr(c("Illinois", "Indiana", "Iowa"), 1, c(1,2,3)) # [1] "I" "In" "Iow"

# substr doesn't replicate input string substr("xxxxxxxxxx", 1, 1:4) # [1] "x"

# substring replicates input string to match other arguments substring("xxxxxxxxxx", 1, 1:4) # [1] "x" "xx" "xxx" "xxxx"

substring("abcde", 1:5, 1:5) # [1] "a" "b" "c" "d" "e"

substring("This is a test", 6) # start from 6th char # [1] "is a test"

x <- c("abcdef", "ghijklmnop") substring(x, 3, 4) <- c("A","BCDF") x # [1] "abAdef" "ghBCklmnop" # substitute one character in first string # substitute two characters in second string

Package base version 6.0.0-69
Package Index