В R строка: str_replace_all не подчиняется 'ignore_case = TRUE' - PullRequest
1 голос
/ 11 апреля 2020

Это ошибка в str_replace_all или я действительно что-то неправильно понимаю?

library(tidyverse)
packageVersion("tidyverse")
# [1] ‘1.2.1’
R.version.string
# [1] "R version 3.5.2 (2018-12-20)"

fruits <- c("one apple", "two pears", "three bananas")

Это работает, как и ожидалось:

fruits %>%
  str_replace_all(c("on\\w+" = "1", "two" = "2", "three" = "3"))
# [1] "1 apple"   "2 pears"   "3 bananas"

И вот так:

fruits %>% 
  str_replace_all(c(regex("on\\w+", ignore_case = TRUE), "two", "three"),
                  c("1", "2", "3"))
# [1] "1 apple"   "2 pears"   "3 bananas"

Но когда я пытаюсь сделать его независимым от регистра, он не использует ignore_case:

fruits %>% 
  str_replace_all(c(regex("ON\\w+", ignore_case = TRUE), "two", "three"),
                  c("1", "2", "3"))
# [1] "one apple" "2 pears"   "3 bananas"

Кажется, проблема в str_replace_all, а не regex

fruits %>% 
  str_detect(regex("ON\\w+", ignore_case = TRUE))
# [1]  TRUE FALSE FALSE

Для моих целей у меня есть обходной путь, но - есть идеи?

1 Ответ

1 голос
/ 11 апреля 2020

Мы можем использовать (?i)

library(dplyr)
library(stringr)
fruits %>% 
   str_replace_all(c("(?i)ON\\w+", "two", "three"),  as.character(1:3))
#[1] "1 apple"   "2 pears"   "3 bananas"

Или обернуть все внутри regex

fruits %>% 
  str_replace_all(regex(c("ON\\w+", "two", "three"), 
            ignore_case = TRUE), c('1', '2', '3'))
 #[1] "1 apple"   "2 pears"   "3 bananas"
...