psub
calls gsub
for each pattern / replacement
pair. Where a pattern is not found, a warning is issued and nothing is
replaced for that pattern / replacement pair. Unlike
gsub
, the first argument is the vector where matches
are sought, meaning that it can be easily used in a pipeline.
Arguments
- x
A character vector.
- pattern
A vector of patterns to replace.
- replacement
A character vector of the same length as
pattern
with the corresponding replacements.- exact
A logical to denote whether
pattern
is to be an exact match (the default). When FALSE,pattern
is treated as a regular expression.- ...
Other arguments to
gsub
.
Details
The default behaviour is to look for an exact match of pattern. This means
that only those elements in x
that fully match pattern
are
replaced. See examples for how this works in practice.
Examples
# Capitalise some letters
psub(letters[1:7], c("a", "c", "e"), c("A", "C", "E"))
#> [1] "A" "b" "C" "d" "E" "f" "g"
# By default exact matches are sought
psub("ace", c("a", "c", "e"), c("A", "C", "E"))
#> Warning: "a" not found in `x`.
#> Warning: "c" not found in `x`.
#> Warning: "e" not found in `x`.
#> [1] "ace"
# Use exact = FALSE to replace a regular expression
psub("ace", c("a", "c", "e"), c("A", "C", "E"), exact = FALSE)
#> [1] "ACE"
# Replace selected values in a vector
psub(c("one", "two", "three"), c("one", "three"), c("ONE", "THREE"))
#> [1] "ONE" "two" "THREE"