[R] gsub patterns from vector elements w/out loop?

Marc Schwartz marc_schwartz at me.com
Mon Feb 22 17:49:18 CET 2010


On Feb 22, 2010, at 10:25 AM, Marianne Promberger wrote:

> Dear list,
> 
> I have two vectors:
> 
> x <- c("one","two")
> y <- paste(rep(x,2),"blah")
> 
> I want to replace all occurrences of each element of x in y with
> something else, so that y looks like this:
> 
> y
> [1] "something else blah" "something else blah" "something else blah"
> [4] "something else blah"
> 
> I can do this using a loop:
> 
> for ( i in 1:length(x) ) {
>  y <- gsub(x[i],"something else",y)
> }
> 
> Surely, there must be a less kludgy way? 
> 
> I tried looking at the different apply()s but am not getting anywhere,
> partly because I lack the mental flexibility to combine the fact that
> I am applying gsub() to y but now want to apply that to x ...  erm. :/
> 
> Marianne

You can use "|" to specify a logical "or" in the search regex:

> gsub("one|two", "something else", y)
[1] "something else blah" "something else blah" "something else blah"
[4] "something else blah"


Thus:

> paste(x, collapse = "|")
[1] "one|two"


and finally:

> gsub(paste(x, collapse = "|"), "something else", y)
[1] "something else blah" "something else blah" "something else blah"
[4] "something else blah"


See ?regex and ?paste

HTH,

Marc Schwartz



More information about the R-help mailing list