str_replace character vector with multiple pattern and multiple repleacements [duplicate]
Question
Possible Duplicate:
Conditional gsub replacement
How can I replace certian elements of a character vector with defined replacements?
county <- c("wagner", "mccain", "mcclain", "dallas")
pattern <- c("mccain", "mcclain", "mcdonald")
replacement <- c("mc cain", "mc clain", "mc donald")
library(stringr)
str_replace(county, pattern, replacement)
Seems like this should be simple but I have been messing with it for a long time and cant figure it out. Any assistance would be greatly appreciated.
La solution
If I understand correctly your question, you don't want to use regular expressions to do a search-and-replace (via gsub
for example). In that matter, the use of the variable name pattern
may have been misleading.
Instead, you just want to do a plain substitution where you have an exact match. You need to use match
and ifelse
:
ifelse(is.na(idx <- match(county, pattern)), county, replacement[idx])
# [1] "wagner" "mc cain" "mc clain" "dallas"
You can also put that in a function:
substitute.all <- function(pattern, replacement, x) {
idx <- match(x, pattern)
return(ifelse(is.na(idx), x, replacement[idx]))
}
substitute.all(pattern, replacement, county)
# [1] "wagner" "mc cain" "mc clain" "dallas"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow