str_replace character vector with multiple pattern and multiple repleacements [duplicate]

StackOverflow https://stackoverflow.com/questions/12322264

  •  30-06-2021
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione

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"  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top