как использовать границы с str_detect (пакет tidyr) - PullRequest
1 голос
/ 11 февраля 2020

Вот некоторые данные.

library(stringr)
library(dplyr)

df <- tibble(sentences)

Я хочу отождествить все предложения со словом «она». Но это, конечно, также возвращает предложения со словами, такими как «там» и «здесь».

df %>% filter(str_detect(sentences, "her"))
# A tibble: 43 x 1
   sentences                                    
   <chr>                                        
 1 The boy was there when the sun rose.         
 2 Help the woman get back to her feet.         
 3 What joy there is in living.                 
 4 There are more than two factors here.        
 5 Cats and dogs each hate the other.           
 6 The wharf could be seen at the farther shore.
 7 The tiny girl took off her hat.              
 8 Write a fond note to the friend you cherish. 
 9 There was a sound of dry leaves outside.     
10 Add the column and put the sum here. 

Документация для stringr::str_detect гласит: «Сопоставить границы символов, слов, строк и предложений с boundary() «. Я не могу понять, как это сделать, и нигде не могу найти пример. Все примеры документации касаются функций str_split или str_count.

Мой вопрос связан с этим вопросом , но я бы особенно хотел понять, как использовать stringr::boundary функция.

1 Ответ

2 голосов
/ 11 февраля 2020

Мы можем указать границу слова (\\b) в начале и в конце, чтобы избежать частичного совпадения

library(stringr)
library(dplyr)
df %>% 
    filter(str_detect(sentences, "\\bher\\b"))
#                             sentences
#1 Help the woman get back to her feet.
#2      The tiny girl took off her hat.

Или использовать boundary для переноса

df %>%
      filter(str_detect(sentences, boundary("her")))
...