str_replace | R Documentation |
Vectorised over string
, pattern
and replacement
.
str_replace(string, pattern, replacement) str_replace_all(string, pattern, replacement)
string |
|
pattern |
|
replacement |
|
Returns a character vector
.
str_replace_na()
to turn missing values into NA
.
fruits <- c("one apple", "two pears", "three bananas") str_replace(fruits, "[aeiou]", "-") str_replace_all(fruits, "[aeiou]", "-") str_replace_all(fruits, "b", NA_character_) str_replace(fruits, "([aeiou])", "") str_replace(fruits, "([aeiou])", "\\1\\1") # Note that str_replace() is vectorised along text, pattern, and replacement str_replace(fruits, "[aeiou]", c("1", "2", "3")) str_replace(fruits, c("a", "e", "i"), "-") # If you want to apply multiple patterns and replacements to the same # string, pass a named vector to pattern. fruits2 <- "one apple---two pears---three bananas" str_replace_all(fruits2, c("one" = "1", "two" = "2", "three" = "3")) # Use a function for more sophisticated replacement. This example converts # all vowels into upper case. str_replace_all(fruits, "[aeiou]", toupper) # If the function used for replacement outputs a longer string than the match # it will replace, a warning is produced. This example tries to replace # colour names with their hex values, which works with stringr but not with # this package unfortunately. colours <- str_c("\\b", colors(), "\\b", collapse="|") col2hex <- function(col) { rgb <- col2rgb(col) rgb(rgb["red", ], rgb["green", ], rgb["blue", ], max = 255) } x <- c( "Roses are red, violets are blue", "My favourite colour is green" ) ## Not run: str_replace_all(x, colours, col2hex) # produces warnings
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.