[R] gsub patterns from vector elements w/out loop?
Bert Gunter
gunter.berton at gene.com
Mon Feb 22 20:08:11 CET 2010
I don't now whether or not this is less "kludgy" than the explicit loop
(loops are implicitly used anyway), but
Reduce(function(x1,x2)gsub(x2,"something else",x1),x, init=y)
does it using gsub. Note, however, that this will **not** work if the
"something else" regular expression itself contained elements of x in the
"wrong" order. I leave it as an exercise to figure out why not. Note also
that this is almost certainly less efficient than your "kludgy" loop, too.
Cheers,
Bert
Bert Gunter
Genentech Nonclinical Biostatistics
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Christian Raschke
Sent: Monday, February 22, 2010 10:20 AM
To: r-help at r-project.org
Subject: Re: [R] gsub patterns from vector elements w/out loop?
Marianne,
The function substring2 from the Hmisc packages works nicely for me to
do this (without explicit gsub, though):
x<- c("one","two")
y<- paste(rep(x,2),"blah")
y
[1] "one blah" "two blah" "one blah" "two blah"
substring2(y,x)<- "something else"
y
[1] "something else blah" "something else blah" "something else blah"
"something else blah"
Christian
On 02/22/2010 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
>
>
--
Christian Raschke
Department of Economics
and
ISDS Research Lab (HSRG)
Louisiana State University
Patrick Taylor Hall, Rm 2128
Baton Rouge, LA 70803
(225)226-0017
crasch2 at lsu.edu
______________________________________________
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