メモ:stringr::str_locate_all()の結果をstringr::str_sub()に渡したいときはpurrr::map2()

例えば、適当な文字列からaで始まる単語を抜き出してみる(こんなことはstr_locate_all()を使わなくてもできるけど、まあ例ということで)

library(stringr)
library(purrr)

x <- c("asymmetry between apple and banana", "aspiration after surgery")

# \\p{Ll}はunicode property nameというやつらしい。
ptn <- "a[\\p{Ll}]+"

str_locate_all()の結果はリストなので、そのままではstr_subに渡せない

m <- str_locate_all(x, ptn)
m
#> [[1]]
#>      start end
#> [1,]     1   9
#> [2,]    11  17
#> [3,]    19  23
#> [4,]    25  27
#> [5,]    29  34
#> 
#> [[2]]
#>      start end
#> [1,]     1  10
#> [2,]    12  16
#> [3,]    18  24
#> 

str_sub(x, m)
#> Error in stri_sub(string, from = start, to = end): (list) object cannot be coerced to type 'integer'

purrrのmap2()でいける

map2(x, m, ~ str_sub(.x, .y))
#> [[1]]
#> [1] "asymmetry" "apple"     "and"       "anana"    
#> 
#> [[2]]
#> [1] "aspiration" "after"