0

I am trying to write a code in R to change all "non" word to "none" in a string but I don't want to change any other words, specially I don't want to change "none" to "nonee".

I tried this code:

gsub("non","none", "non none", fixed = TRUE)

but result is:

"none nonee"

Is there anyway to do this using R's gsub?

Soroosh
  • 477
  • 2
  • 7
  • 18

1 Answers1

0

You can use word boundaries...

x <- c("non" , "none")
gsub( "\\bnon\\b" , "none" , x )
#[1] "none" "none"
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • What was wrong with x <- c("non" , "none") gsub( "^non$" , "none" , x ) ? – Soroosh Dec 02 '13 at 21:59
  • @Soroosh what do you expect to happen with a string such as `"I wanted non other than the best"`? `^` and `$` anchor the start and end of the entire string respectively. `\\b` just anchors either side of the word bondary. – Simon O'Hanlon Dec 02 '13 at 22:01
  • 1
    I want to change it to "I wanted none other than the best" - thanks I got the point – Soroosh Dec 02 '13 at 22:04