Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: GSUB looping over replacement characters

Tags:

r

gsub

I am trying to replace several strings within a string, using gsub. In the general case gsub(pattern, replacement, x) takes a character vector x , but both pattern and replacement are assumed to be characters or regular expressions. pattern and replacement cannot be a vector of characters.

I can implement this crudely using a loop but in my case both pattern and replacement are long vectors, so i am hoping for a "vectorized" implementation if possible

My current implementation is as follows:

    strs<-"apples.in.bed"
    replace.vect<-c("a","e","i")
    new.char.vect<-c("1","2","3")
    temp <- strs
    for(i in 1:length(replace.vect)){
      temp<-gsub(replace.vect[i], new.char.vect[i],temp)
    }

    # temp: "1ppl2s.3n.b2d"

However, I'd like to arrive at the same result without the use of the for loop. I have also tried using apply, but internally it seems as though all the characters are being looped over, so it does not seem to offer much in terms of performance gain;

    apply(cbind(replace.vect, new.char.vect),1,function(x) {strs<<-gsub(x[1],x[2],strs)})

Also - I have also considered the chartr function as shown here, but this function replaces characters with characters, but cannot replace strings with strings.

Any suggestions highly appreciated!

like image 767
JSB Avatar asked Dec 07 '25 21:12

JSB


1 Answers

You could try the sedit function from the Hmisc library

library(Hmisc)
sedit(text = strs, replace.vect, new.char.vect)
#[1] "1ppl2s.3n.b2d"
like image 53
JoeArtisan Avatar answered Dec 09 '25 10:12

JoeArtisan