replacing several string occurrences in r

227 views Asked by At

I want to replace several strings with one. I've researched and found that gsub can replace elements but one at a time.

If I do this I get a warning saying that only the first one was used.

data$EVTYPE <- gsub( c("x","y") , "xy", data$EVTYPE)

I am trying now with sapply

data$EVTYPE <- sapply(data$EVTYPE, gsub, c("x", "y"), "xy") but it's been already more than 5 minutes and is still processing. I will get a stack overflow message any time now. :-/ Is there an elegant short solution for this? Is there a package I can use for this? It needs to be small because I need to do this for several cases where I have duplicate names.

2

There are 2 answers

0
guergana On BEST ANSWER

Thanks for your useful comments. It was done as Frank suggested. gsub( "x|y" , "xy", data$EVTYPE).

Instead of using a vector.

0
Nick Kennedy On

For the cold temperature case, you could use gsub("COLD TEMPERATURES?", "COLD", data$EVTYPE) it's worth spending a little time getting one's head around the basics of regular expressions. There are lots of tutorials including this one.