CRANからインストール
install.packages("stringr")GitHubからインストール
devtools::install_github("hadley/stringr")githubinstallでもOK
githubinstall::githubinstall("stringr")str_c("kosaki", "love", sep = " ")## [1] "kosaki love"
paste()と同じように使えるx <- c("kosaki", "chitoge", "marika")
str_c(x, collapse = ", ")## [1] "kosaki, chitoge, marika"
collapse=オプションを使用paste()と同様y <- c("love", "like", "like")
(ni <- str_c(x, y, sep="-"))## [1] "kosaki-love" "chitoge-like" "marika-like"
str_split(ni, pattern = "-")## [[1]]
## [1] "kosaki" "love"
##
## [[2]]
## [1] "chitoge" "like"
##
## [[3]]
## [1] "marika" "like"
str_split(ni, pattern = "-", simplify = TRUE)## [,1] [,2]
## [1,] "kosaki" "love"
## [2,] "chitoge" "like"
## [3,] "marika" "like"
simplify=TRUEで行列型で返すstr_split("k-o-s-a-k=i", pattern = "-", n=3)## [[1]]
## [1] "k" "o" "s-a-k=i"
n=オプションで,分割数を指定することも可能a <- c("kosaki-love","chitoge-like","tugumi")
str_split_fixed(a, pattern="-", n=2)## [,1] [,2]
## [1,] "kosaki" "love"
## [2,] "chitoge" "like"
## [3,] "tugumi" ""
str_split()同様,文字列を分割x <- c("kosaki", "chitoge", "marika")
str_detect(x, pattern="ko")## [1] TRUE FALSE FALSE
str_detect(x,pattern="a$")## [1] FALSE FALSE TRUE
str_subset(x, pattern="o")## [1] "kosaki" "chitoge"
str_replace(x, pattern="k", replacement="*")## [1] "*osaki" "chitoge" "mari*a"
str_replace_all(x, pattern="k", replacement="*")## [1] "*osa*i" "chitoge" "mari*a"
str_extract(x, pattern="ko")## [1] "ko" NA NA
str_extract_all(x, pattern="k|s", simplify=TRUE)## [,1] [,2] [,3]
## [1,] "k" "s" "k"
## [2,] "" "" ""
## [3,] "k" "" ""
simplify=TRUEで行列にstr_sub(x, start=1, end=4)## [1] "kosa" "chit" "mari"
str_sub(x, start=4, end=-1)## [1] "aki" "toge" "ika"
str_conv(x, encoding="UTF-8")iconv()と同じようなものstr_view(x, "a$")str_match()str_count()str_locate()str_length()str_dup()スクレイピングして取得したデータを前処理するとき
tibble::rownames_to_column(mtcars, var = "name") %>%
dplyr::filter(str_detect(.$name, "Mazda"))## name mpg cyl disp hp drat wt qsec vs am gear carb
## 1 Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
## 2 Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
今日の資料置き場 - https://kazutan.github.io/SappoRoR7