11

次のような文字列の文字ベクトルがあります。

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+","_")

しかし、これを1つのコマンドで実行できますか?次のような出力を取得できます:

x
[1]"weather_is_good_today"
[2]"it_will_rain_tomorrow"
[3]"do_not_get_angry"

助けてくれてありがとう。

4

2 に答える 2

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

"weather_is_good_today"  "it__will_rain_tomorrow" "do_not__get_angry" 
于 2012-12-21T06:24:59.650 に答える
4

これを試して 。

x1 <- str_replace_all(x,"[[:punct:]\\\s]+","_")

R の知識がありません。Wikiで確認した正規表現に基づいて回答を提案しました。

于 2012-12-21T06:28:17.123 に答える