gsub - Match and replace multiple strings in a vector of text without looping in R -
i trying apply gsub in r replace match in string corresponding match in string b. example:
a <- c("don't", "i'm", "he'd") b <- c("do not", "i am", "he would") c <- c("i'm going party", "he'd go too") newc <- gsub(a, b, c)
such newc = "i going party", "he go too") approach not work because gsub accepts string of length 1 , b. executing loop cycle through , b slow since real , b have length of 90 , c has length > 200,000. there vectorized way in r perform operation?
1) gsubfn gsubfn
in gsubfn package gsub
except replacement string can character string, list, function or proto object. if list replace each matched string component of list name equals matched string.
library(gsubfn) gsubfn("\\s+", setnames(as.list(b), a), c)
giving:
[1] "i going party" "he go too"
2) gsub solution no packages try loop:
cc <- c for(i in seq_along(a)) cc <- gsub(a[i], b[i], cc, fixed = true)
giving:
> cc [1] "i going party" "he go too"
Comments
Post a Comment