我有这样的字符串的字符向量:
x <- c("weather is good_today","it. will rain tomorrow","do not* get_angry")
我想替换所有特殊字符和空格,并用“_”替换它们。
我使用str_replace all
中的stringr package
,如下所示:
x1 <- str_replace_all(x,"[[:punct:]]","_")
x2 <- str_replace_all(x1,"\\s+","_")
但这可以在一个命令中完成,我可以得到这样的输出:
x
[1]"weather_is_good_today"
[2]"it_will_rain_tomorrow"
[3]"do_not_get_angry"
感谢您的帮助。
答案 0 :(得分:17)
gsub('([[:punct:]])|\\s+','_',x)
"weather_is_good_today" "it__will_rain_tomorrow" "do_not__get_angry"
答案 1 :(得分:4)