Свободная текстовая категоризация через grep в R - PullRequest
0 голосов
/ 02 мая 2020

Я R newb ie. Мне нужно разбить свободный текст (отзывы клиентов) на фиксированное количество категорий. Я пытаюсь запустить небольшой код для проверки логики c.

a<-c("a","b","c","d","e") # Category a - if the free text contains any of "a","b","c","d" or "e"
b<-c("f","g","h","i","j") # Category b - if the free text contains any of "f","g","h","i" or "j"
check<-c("a","g","d","j") # Free text to be categorized. "a" should be categorized as a; "g" as b; "d" as a and
                          # "j" as b
count<-length(check)
output<-vector(mode="list",length = count) # Empty categorized list - targeted output is (a,b,a,b)
for (i in 1:count) {
 output[i]<-ifelse(grepl(a,check[i]),"a",ifelse(grepl(b,check[i]),"b","other"))
}

Я получаю следующие предупреждения:

1. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
2. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
3. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
4. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
5. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
6. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
7. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used

Вывод выходит как (a, other, other , прочее)

Либо grepl не подходит для использования, либо, возможно, есть способ использовать векторный шаблон. Запрос вашей помощи и руководства.

Ответы [ 2 ]

1 голос
/ 02 мая 2020

grepl жалуется, потому что «шаблон» (первый аргумент) содержит несколько шаблонов вместо одного. Одним из способов решения этой проблемы было бы сведение ваших условий в одно регулярное выражение (| обозначает 'или'), например:

a<-c("a","b","c","d","e") # Category a - if the free text contains any of "a","b","c","d" or "e"
b<-c("f","g","h","i","j") # Category b - if the free text contains any of "f","g","h","i" or "j"
check<-c("a","g","d","j") # Free text to be categorized. "a" should be categorized as a; "g" as b; "d" as a and
# "j" as b

# collapse regular expression
a <- paste(a, collapse = "|")
b <- paste(b, collapse = "|")

count<-length(check)
output<-vector(mode="list",length = count) # Empty categorized list - targeted output is (a,b,a,b)
for (i in 1:count) {
  output[i]<-ifelse(grepl(a,check[i]),"a",ifelse(grepl(b,check[i]),"b","other"))
}

output

, которое возвращает

[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "a"

[[4]]
[1] "b"
0 голосов
/ 02 мая 2020

Это не отвечает на вопрос, который вы задали, но ... Похоже, вы заново изобретаете колесо. Я предлагаю вам проверить

  • Пакет tm (для интеллектуального анализа текста)
  • Text Mining с R , Silge и Robinson, от O'Reilly , особенно глава 2, Анализ настроений с аккуратными данными
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...