Montag, 1. März 2010

R Search and Replace

How can one replace certain characters or sequences of characters in a string?

I searched for a function that does that for quite a while but to no avail. But, using the strsplit & paste functions, one can do it like this:

streplace <- function(string, searchterm, replacestring) {
    string <- paste(strsplit(string,paste("[",searchterm,"]", sep=""))[[1]], collapse=replacestring);
    return(string);
}

With the usage for example: htmlstring = streplace(mytext, "ä", "&auml;")

Keine Kommentare:

Kommentar veröffentlichen