Consider "artikelnr"
. I want to replace "nr"
by "nummer"
, but when I consider "inrichting"
, I do NOT want to replace "nr"
. So I just want to replace "nr"
by "nummer"
if it's at the end of a word.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
regex
is your friend, here:
sub('nr$', 'nummer', 'artikelnr')
# [1] "artikelnummer"
The $
indicates "end of string", so nr
will only be replaced with nummer
when it appears at the end of the string.
sub
can operate on an entire vector, e.g. for a character vector x
, do:
sub('nr$', 'nummer', x)
回答2:
If you don't mind using the stringr
package, str_replace is also handy :
library(stringr)
str_replace("artikelnr", "nr$", "nummer")