R言語:stringrパッケージを使った文字列処理

Detect Matches

str_detect:マッチした文字列の有無(論理値)

#指定した文字列を含むかどうか(パターンマッチするかどうか)を論理値(TRUEかFALSE)で判定します

test_det1 <- c("北海道", "岩手県", "東京都", "京都", "鹿児島県")
str_detect(test_det1, pattern="(都|府)")
[1] FALSE FALSE  TRUE  TRUE FALSE 

str_starts/str_ends:始まり/終わりの文字の有無(論理値)

#指定した文字から始まる文字列を含むかどうか(パターンマッチするかどうか)を論理値(TRUEかFALSE)で判定します

test_sten <- c("北海道", "岩手県", "東京都", "京都", "鹿児島県")
str_starts(test_sten, pattern="(北|東)")
[1]  TRUE FALSE  TRUE FALSE FALSE
str_ends(test_sten, pattern="(県|都)")
[1] FALSE  TRUE  TRUE  TRUE  TRUE

#「negate = TRUE」オプションを使うと、逆に指定した文字む文字列を「FALSE」として返します

str_starts(test_sten, pattern="(北|東)", negate = TRUE)
[1] FALSE  TRUE FALSE  TRUE  TRUE
str_ends(test_sten, pattern="(県|都)", negate = TRUE)
[1]  TRUE FALSE FALSE FALSE FALSE

Subset Strings

str_sub : 文字列を抽出

#「str_sub」は位置を数字で指定して文字を抽出できます

#抽出

test_su1 <- c("sringr", "文字列処理")
str_sub(test_su1, start = 2, end = 4) #先頭から2−4文字
[1] "rin"    "字列処"
str_sub(test_su1, start = -4, end = -2) #後ろから4−2文字
[1] "ing"    "字列処"

#変換への応用
#例えば文字列の先頭に余計な文字(下の例では",")が入っていた場合その文字を変換可能です
#先頭1文字をブランクに変換した例です

test_su2 <- c(",sringr", ",文字列処理")
#上の2つの文字列の先頭(start=end=1)をそれぞれ「""」に置き換えます
str_sub(test_su2, start = 1, end = 1) <- c("", "") 
test_su2
[1] "sringr"     "文字列処理"

str_subset:パターンマッチ

#指定した文字列を含むかどうか(パターンマッチするかどうか)を判定します

test_st1 <- c("北海道", "岩手県", "東京都", "京都", "鹿児島県")
str_subset(test_st1, pattern="(都|府)")
[1] "東京都" "京都"  

#正規表現を使用することも可能です。
#先頭に「京」がある文字列を指定した例です

str_subset(test_st1, pattern="^京")
[1] "京都"

str_extract:パターンマッチした文字列の抽出(先頭一致)

#パターンマッチした(先頭の)文字列のみ抽出します

str_extract(test_ext1, pattern="県")
[1] NA   "県" NA   NA   "県"
str_extract(test_ext1, pattern="(県|道)")
[1] "道" "県" NA   NA   "県"

str_extract_all:パターンマッチした全ての文字列の抽出

#パターンマッチした全文字列を抽出します

test_ext2 <- c("hokkaido", "iwate", "toukyou", "kyouto", "kagoshima")
str_extract_all(test_ext2, pattern="o")
[1] "道" "県" NA   NA   "県"
[[1]]
[1] "o" "o"

[[2]]
character(0)

[[3]]
[1] "o" "o"

[[4]]
[1] "o" "o"

#デフォルトではリスト型で返します。以下で確認しています

tr_extract_all(test_ext2, pattern="o") %>% class()

[1] "list"
#「simplify=TRUE」を使うことで行列(matrix)型の出力に変更できます

str_extract_all(test_ext2, pattern="o" ,simplify=TRUE)
[,1] [,2]
[1,] "o"  "o" 
[2,] ""   ""  
[3,] "o"  "o" 
[4,] "o"  "o" 
[5,] "o"  ""

str_extract_all(test_ext2, pattern="o" ,simplify=TRUE) %>% class()
[1] "matrix" "array" 

Manage Length

str_length : 文字列長

#「str_length」は文字列の長さを返す関数です

library(stringr)

test_le1 <- "sringr"
test_le2 <- "sringr文字列処理"
str_length(c(test_le1, test_le2))
[1]  6 11

test_le3 <- c("北海道", "岩手県", "東京都", "京都", "鹿児島県")
str_length(test_le3)
[1] 3 3 3 2 4

str_trunc:指定した文字数以外を省略

#省略 = 「...」に置換します。アルファベットに使用できます

test_tru <- "There are Apples,Oranges and Bananas."

str_trunc(test_tru, 30, "right")
[1] "There are Apples,Oranges an..."
str_trunc(test_tru, 30, "left")
[1] "...Apples,Oranges and Bananas."
str_trunc(test_tru, 30, "center")
[1] "There are Appl... and Bananas."

str_trim、str_squish : 空白除去

#「str_ltrim」は文字列の前後にある空白を除去する関数です
#「str_squish」は連続する空白文字を1つにまとめます

test_tr1 <- " sringr "
str_trim(test_tr1, "both")
str_trim(test_tr1, "right")
str_trim(test_tr1, "left")
[1] "sringr"
[1] " sringr"
[1] "sringr "

test_tr2 <- "   今日は4   月10日の  日曜日  。   "
str_trim(test_tr2)
[1] "今日は4   月10日の  日曜日  。"
str_squish(test_tr2)
[1] "今日は4 月10日の 日曜日 。"

Mutate Strings

str_replase:マッチした文字列の置換(先頭一致)

#パターンマッチした文字列の先頭のみ置換します

test_rep1 <- c("hokkaido", "iwate", "toukyou", "kyouto", "kagoshima")
str_replace(test_rep1, pattern = "o", replacement = "*")
[1] "h*kkaido"  "iwate"     "t*ukyou"   "ky*uto"    "kag*shima"

str_replase_all:マッチした全ての文字列を置換

#パターンマッチした文字列の先頭のみ置換します

test_rep2<- c("hokkaido", "iwate", "toukyou", "kyouto", "kagoshima")
str_replace_all(test_rep1, pattern = "o", replacement = "*")
[1] "h*kkaid*"  "iwate"     "t*uky*u"   "ky*ut*"    "kag*shima"

#複数の文字列を置換することできます

str_replace_all(test_rep2, c("o" = "O", "k" = "K", "a" = "A"))
[1] "hOkkAidO"  "iwAte"     "tOukyOu"   "kyOutO"    "kAgOshimA"

str_to_lower/upper:小文字/大文字に変換(アルファベット)

test_to <- c("Apple", "Orange", "Banana")

str_to_lower(test_to)
[1] "apple"  "orange" "banana"

str_to_upper(test_to)
[1] "APPLE"  "ORANGE" "BANANA"

str_to_title:文字列の文頭のみを大文字に変換

#「title case」(タイトルケース)という形式に変換します

test_tit <- c("UNITED STATES", "united states", "United states")
str_to_title(test_tit)
[1] "United States" "United States" "United States"

Join and Split

str_c : 結合(連結)

#「str_c 」は文字列を結合させる関数です

test_st1 <- "sringrは"
test_st2 <- "文字列処理"
str_c(test_st1, test_st2)
[1] "sringrは文字列処理"

#「sep」という引数で文字と文字の間位入れる文字列や記号を付与します

test_st3 <- "北海道"
test_st4 <- "東京都"
test_st5 <- "沖縄県"
str_c(test_st3, test_st4, test_st5, sep=",")
[1] "北海道,東京都,沖縄県"

#複数文字列をベクトルで渡すと、それぞれの文字列に文字を結合します

test_st6 <- c("宮城", "神奈川", "福岡")
str_c(test_st6, "県")
[1] "宮城県" "神奈川県" "福岡県

#「collapse」を使えば文字列ベクトルの要素を1つに結合します

str_c(test_st6, "県", collapse=" ")
[1] "宮城県 神奈川県 福岡県"
#なお、標準Rの「paste」を使っても同様の結合でがきます

test_st3 <- "北海道"
test_st4 <- "東京都"
test_st5 <- "沖縄県"
paste(test_st3, test_st4, test_st5, sep=",")
[1] "北海道,東京都,沖縄県"

str_split : 文字列を分割

#「str_split」は指定した文字で文字列を分割します。

test_sp1 <- c("北海道 札幌", "岩手県 盛岡", "東京都 東京")
str_split(test_sp1, pattern = " ")
[[1]]
[1] "北海道" "札幌"  

[[2]]
[1] "岩手県" "盛岡"  

[[3]]
[1] "東京都" "東京" 

#リスト型で出力します

str_split(test_sp1, pattern = " ") %>% class()
[1] "list" #リスト型

#「simplify=TRUE」で行列(マトリクス)型で返すこともできます

str_split(test_sp1, pattern = " ", simplify=T)
[,1]     [,2]  
[1,] "北海道" "札幌"
[2,] "岩手県" "盛岡"
[3,] "東京都" "東京"

str_split(test_sp1, pattern = " ", simplify=T) %>% class()
[1] "matrix" "array"  #マトリックス型

#nオプションで分割数を指定することもできます

test_sp2 <- c("北海道 札幌 市", "岩手県 盛岡 市", "東京都 千代田 区")
#区切られる場所は先頭にある「" "」が優先されます
str_split(test_sp2, pattern = " ", simplify=T, n=2)
[,1]     [,2]       
[1,] "北海道" "札幌 市"  
[2,] "岩手県" "盛岡 市"  
[3,] "東京都" "千代田 区"

str_split(test_sp2, pattern = " ", simplify=T, n=3)
     [,1]     [,2]     [,3]
[1,] "北海道" "札幌"   "市"
[2,] "岩手県" "盛岡"   "市"
[3,] "東京都" "千代田" "区"

参考

CRAN - Package stringr
Simple, Consistent Wrappers for Common String Operations
A consistent, simple and easy to use set of wrappers around the fantastic stringi package. All function and argument names (and positions) are consistent, all f...

 →CHEAT SHEET

タイトルとURLをコピーしました