string 用字符串列表中的空格替换特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13985215/
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
replace special characters along with the space in list of strings
提问by user1021713
I have character vector of strings like this :
我有这样的字符串字符向量:
x <- c("weather is good_today","it. will rain tomorrow","do not* get_angry")
I want to replace all the special characters and space and replace them with "_".
I used str_replace all
from the stringr package
like this :
我想替换所有特殊字符和空格并用“_”替换它们。我用str_replace all
从stringr package
这样的:
x1 <- str_replace_all(x,"[[:punct:]]","_")
x2 <- str_replace_all(x1,"\s+","_")
But can this be done in one single command and I can get the output like this :
但这可以在一个命令中完成吗,我可以得到这样的输出:
x
[1]"weather_is_good_today"
[2]"it_will_rain_tomorrow"
[3]"do_not_get_angry"
Thanks for any help.
谢谢你的帮助。
采纳答案by Abin Manathoor Devasia
回答by agstudy
gsub('([[:punct:]])|\s+','_',x)
"weather_is_good_today" "it__will_rain_tomorrow" "do_not__get_angry"