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

Gabor Grothendieck ggrothendieck at gmail.com
Mon Feb 22 20:00:00 CET 2010


Here are a few possibilities using gsubfn in the gsubfn package

x <- c("one","two")
y <- paste(rep(x,2),"blah")

library(gsubfn)
# 1
gsubfn("\\w+", w ~ if (w %in% x) "something else" else w, y)

# 2
gsubfn("\\w+", list(one = "something else", two = "something else"), y)

# 3
L <- sapply(x, function(...) "something else", simplify = FALSE)
gsubfn("\\w+", L, y)

gsubfn is the same as gsub except the second argument can be a
function, list or certain other objects.

The regular expression "\\w+" matches each word in y and in the first
solution that is replaced with phrase or just returned according to
the function which is specified in formula notation.

The second solution uses the fact that gsubfn allows lists such that
the names of the list components are matched and replaced with the
corresponding contents.

The third is the same as the second except that it uses sapply to
create the list from x.


On Mon, Feb 22, 2010 at 11:55 AM, Marianne Promberger
<marianne.promberger at kcl.ac.uk> wrote:
>
>> > gsub(paste(x, collapse = "|"), "something else", y)
>> [1] "something else blah" "something else blah" "something else blah"
>> [4] "something else blah"
>
> Many thanks! I didn't know about "collapse". Should have thought about
> reading up in ?paste ...
>
> Thanks
>
> 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