replace special characters along with the space in list of strings
Solution 1
try this .
x1 <- str_replace_all(x,"[[:punct:]\\\s]+","_")
I don't have knowledge in R , i suggested the answer based on Regular expression checked withWiki
Solution 2
gsub('([[:punct:]])|\\s+','_',x)
"weather_is_good_today" "it__will_rain_tomorrow" "do_not__get_angry"
user1021713
SOreadytohelp SO has done a lot for me. Thanks to all the developers who have answered my questions. I have asked mostly questions related to R. In the year 2011 when I joined SO, i was just a beginner in R. But slowly the answers in SO and some of my own work raised my interest towards working in R. As a result, I also wanted to contribute to SO and started actively answering questions on SO and started voting as well. Since 2011, it has been wonderful experience on SO. I thank all the people for up-voting and encouraging my questions and answers and also down-voting for constructive feedback. Nowadays I am not very much active on SO. But I will take this opportunity to thank everyone again on SO for helping me.
Updated on July 09, 2022Comments
-
user1021713 almost 2 years
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 thestringr 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.
-
Mike Williamson about 9 yearsThis answer is actually inaccurate. While "str_replace_all" is a nice function, the actual regexpr should be ([[:punct:]])|\\s+)