メモ:stringrのstr_locate_allとstr_subを組み合わせて文字列置換

前回やろうとして分からなかったやつ。

stringr::str_locate_all()というのがあると知ったのでメモ。

こんな感じ。

hoxo <- "This is hoxo_m"
pattern <- "(hoxo)_(m|w|b|x)"
m <- stringr::str_locate(hoxo, pattern)
m
#>      start end
#> [1,]     9  14

# 抜き出し
stringr::str_sub(hoxo, start = m[1], end = m[2])
#> [1] "hoxo_m"

# マッチした部分を置換
stringr::str_sub(hoxo, start = m[1], end = m[2]) <-
    toupper(stringr::str_sub(hoxo, start = m[1], end = m[2]))
hoxo
#> [1] "This is HOXO_M"

でも複数はちょっと難しい。

hoxos <- c("This is hoxo_m", "This is hozo_m", "This is hoxo_b")
pattern <- "(hoxo)_(m|w|b|x)"

m <- stringr::str_locate(hoxos, pattern)
m
#>      start end
#> [1,]     9  14
#> [2,]    NA  NA
#> [3,]     9  14

stringr::str_sub(hoxos, start = m[,1], end = m[,2]) <-
    purrr::map_chr(stringr::str_sub(hoxos, start = m[,1], end = m[,2]), toupper)
hoxos
#> [1] "This is HOXO_M" NA               "This is HOXO_B"

ひとつNAになってしまった…。ちょっと工夫が必要そうです。