Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace special characters along with the space in list of strings

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 :

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.

like image 555
user1021713 Avatar asked Dec 21 '12 06:12

user1021713


1 Answers

 gsub('([[:punct:]])|\\s+','_',x)

"weather_is_good_today"  "it__will_rain_tomorrow" "do_not__get_angry" 
like image 94
agstudy Avatar answered Oct 01 '22 06:10

agstudy