LoginSignup
2
2

More than 5 years have passed since last update.

文字列の置換で置換対象と置換文字列をベクトルで指定する(stringr編)

Last updated at Posted at 2016-04-27

文字列ベクトルの各要素を調べ、「桜」という文字列があれば「桑」に、さらに「ぶどう」があれば「もも」に変換する

> library(stringr)
> ## もとの文字列ベクトル
> x <- c("桜の実", "山ぶどう", "たけのこの里", "きのこの山", "水まんじゅう" )
>
> ## 置換対象を名前付きベクトルで与える
> y <- c(桜 =  "桑", ぶどう = "もも")
> 
> str_replace_all (x, y)
[1] "桑の実"     "山もも"    "たけのこの里"    "きのこの山" 

余計な文字を切り詰める。「桜の実」なら「桜」に、「たけのこの里」なら「たけのこ」にする。

> str_replace_all (x, ".*(桜|ぶどう|たけのこ|きのこ).*", "\\1")
> # str_replace_all (x, "(.*)(桜|ぶどう|たけのこ|きのこ)(.*)", "\\2")
[1] "桜"   "ぶどう"   "たけのこ"   "きのこ"   "水まんじゅう"  

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2