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

Benilton Carvalho beniltoncarvalho at gmail.com
Mon Feb 22 17:48:19 CET 2010


gsub("one|two", "something else", y)

?

On Mon, Feb 22, 2010 at 4:25 PM, Marianne Promberger
<marianne.promberger at kcl.ac.uk> 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
>
> --
> Marianne Promberger PhD, King's College London
> http://promberger.info
> R version 2.10.1 (2009-12-14)
> Ubuntu 9.10
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list