Reputation: 217
I would like to remove the word "amp" in the below sentence.
original:
x <- 'come on ***amp*** this just encourages the already rampant mispronunciation of phuket'
What I want:
x <- 'come on this just encourages the already rampant mispronunciation of phuket'
However, if I used gsub
, the "amp" in the word of "rampant" will be removed as well which is NOT the case I want. Can I know what function should I use in this case?
> gsub("amp","", x)
[1] "come on this just encourages the already rant mispronunciation of phuket"
Upvotes: 0
Views: 4329
Reputation: 99331
You could just find the occurrence of "amp" that has a space in front.
> gsub("\\samp", "", x)
## [1] "come on this just encourages the already rampant mispronunciation of phuket"
where \\s
means space. This is more readable as
> gsub(" amp", "", x)
Upvotes: 0
Reputation: 60924
You could also split the string into words, and then compare:
x <- 'come on this just encourages the already rampant mispronunciation of phuket'
split_into_words = strsplit(x, ' ')[[1]]
filtered_words = split_into_words[!split_into_words == 'amp']
paste(filtered_words, collapse = ' ')
[1] "come on this just encourages the already rampant mispronunciation of phuket"
Upvotes: 1
Reputation: 81683
You can use this regex:
gsub("\\bamp\\b","", x)
# [1] "come on this just encourages the already rampant mispronunciation of phuket"
The \\b
means word boundary.
Upvotes: 1