string R 替换字符串中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18070251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
R Replace word in a string
提问by Leroy Tyrone
I have inherited an r project that has a dataframe with truncated text strings. Based on some responses in this forum, I have tried
我继承了一个 r 项目,它有一个带有截断文本字符串的数据框。根据本论坛的一些回复,我尝试过
temp$taname2 <- gsub("\bDistr\b", "District", temp$taname2)
This did not work. I tried
这没有用。我试过
temp$taname2 <- gsub("Distr", "District", temp$taname2)
but this resulted in rows already containing the word "District" being changed to "Districtic", "Districtict", or similar. I also tried
但这导致已经包含单词“District”的行被更改为“Districtic”、“Districtic”或类似的。我也试过
temp$taname2[grep("\bDistr\b",temp$taname2)] <- "District"
but, alas, no luck.
但是,唉,没有运气。
I realise the answer is ridiculously simple but I haven't been able to work out how to do it.
我意识到答案非常简单,但我一直无法弄清楚如何去做。
Thanks in advance.
提前致谢。
采纳答案by Kenty Ramdatt
You need to make use of regular expressions as well as the gsub function. I think this question is answered here: In R, replace text within a string
您需要使用正则表达式以及 gsub 函数。我认为这个问题在这里得到了回答:在 R 中,替换字符串中的文本
Hope this helps.
希望这可以帮助。