" xx yy 11 22 33 "
となります"xxyy112233"
。どうすればこれを達成できますか?
9 に答える
一般に、ベクトル化されたソリューションが必要なので、より良いテスト例を次に示します。
whitespace <- " \t\n\r\v\f" # space, tab, newline,
# carriage return, vertical tab, form feed
x <- c(
" x y ", # spaces before, after and in between
" \u2190 \u2192 ", # contains unicode chars
paste0( # varied whitespace
whitespace,
"x",
whitespace,
"y",
whitespace,
collapse = ""
),
NA # missing
)
## [1] " x y "
## [2] " ← → "
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA
ベース R アプローチ:gsub
gsub
fixed = TRUE
文字列 ( ) または正規表現 ( fixed = FALSE
、デフォルト)のすべてのインスタンスを別の文字列に置き換えます。すべてのスペースを削除するには、次を使用します。
gsub(" ", "", x, fixed = TRUE)
## [1] "xy" "←→"
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA
DWin が指摘したように、この場合fixed = TRUE
は必要ありませんが、固定文字列の一致は正規表現の一致よりも高速であるため、パフォーマンスがわずかに向上します。
すべての種類の空白を削除する場合は、次を使用します。
gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "←→" "xy" NA
gsub("\\s", "", x) # same; note the double backslash
library(regex)
gsub(space(), "", x) # same
"[:space:]"
すべての空白文字に一致する R 固有の正規表現グループです。 \s
同じことを行う、言語に依存しない正規表現です。
stringr
アプローチ:str_replace_all
およびstr_trim
stringr
は、基本 R 関数の周りにより人間が読めるラッパーを提供します (ただし、2014 年 12 月の時点で、開発バージョンには の上に構築されたブランチがありstringi
ます。後述)。[ を使用した上記のコマンドの等価物は次のとおりstr_replace_all][3]
です。
library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")
stringr
str_trim
先頭と末尾の空白のみを削除する機能もあります。
str_trim(x)
## [1] "x y" "← →" "x \t\n\r\v\fy" NA
str_trim(x, "left")
## [1] "x y " "← → "
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA
str_trim(x, "right")
## [1] " x y" " ← →"
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA
stringi
アプローチ:stri_replace_all_charclass
およびstri_trim
stringi
は、プラットフォームに依存しないICU ライブラリに基づいて構築されており、広範な文字列操作関数のセットを備えています。上記と同等のものは次のとおりです。
library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")
空白と"\\p{WHITE_SPACE}"
見なされる Unicode コード ポイントのセットの代替構文を次に示します。より複雑な正規表現の置換については、 もあります。"[[:space:]]"
"\\s"
space()
stri_replace_all_regex
stringi
トリム機能も搭載。
stri_trim(x)
stri_trim_both(x) # same
stri_trim(x, "left")
stri_trim_left(x) # same
stri_trim(x, "right")
stri_trim_right(x) # same
str_trim( , side="both") を使用して文字列の先頭と末尾から空白を削除する「stringr」パッケージについて学びましたが、次のような置換関数もあります。
a <- " xx yy 11 22 33 "
str_replace_all(string=a, pattern=" ", repl="")
[1] "xxyy112233"
上記のソウルションはスペースのみを削除することに注意してください。パッケージstri_replace_all_charclass
からタブまたは改行の使用も削除したい場合。stringi
library(stringi)
stri_replace_all_charclass(" ala \t ma \n kota ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"
tidyverse のstr_squish()
パッケージの関数は魔法のようです!stringr
library(dplyr)
library(stringr)
df <- data.frame(a = c(" aZe aze s", "wxc s aze "),
b = c(" 12 12 ", "34e e4 "),
stringsAsFactors = FALSE)
df <- df %>%
rowwise() %>%
mutate_all(funs(str_squish(.))) %>%
ungroup()
df
# A tibble: 2 x 2
a b
<chr> <chr>
1 aZe aze s 12 12
2 wxc s aze 34e e4