Como calcular a proximidade de palavras com um termo específico em um documento
Estou tentando descobrir uma maneira de calcular proximidades de palavras para um termo específico em um documento, bem como a proximidade média (por palavra). Eu sei que existem perguntas semelhantes sobre o SO, mas nada que me dê a resposta que eu preciso ou até me aponte para algum lugar útil. Então, digamos que tenho o seguinte texto:
song <- "Far over the misty mountains cold To dungeons deep and caverns old We
must away ere break of day To seek the pale enchanted gold. The dwarves of
yore made mighty spells, While hammers fell like ringing bells In places deep,
where dark things sleep, In hollow halls beneath the fells. For ancient king
and elvish lord There many a gleaming golden hoard They shaped and wrought,
and light they caught To hide in gems on hilt of sword. On silver necklaces
they strung The flowering stars, on crowns they hung The dragon-fire, in
twisted wire They meshed the light of moon and sun. Far over the misty
mountains cold To dungeons deep and caverns old We must away, ere break of
day, To claim our long-forgotten gold. Goblets they carved there for
themselves And harps of gold; where no man delves There lay they long, and
many a song Was sung unheard by men or elves. The pines were roaring on the
height, The winds were moaning in the night. The fire was red, it flaming
spread; The trees like torches blazed with light. The bells were ringing in
the dale And men they looked up with faces pale; The dragon’s ire more fierce
than fire Laid low their towers and houses frail. The mountain smoked beneath
the moon; The dwarves they heard the tramp of doom. They fled their hall to
dying fall Beneath his feet, beneath the moon. Far over the misty mountains
grim To dungeons deep and caverns dim We must away, ere break of day,
To win our harps and gold from him!"
Quero poder ver quais palavras aparecem em 15 (gostaria que esse número fosse intercambiável) palavras de ambos os lados (15 à esquerda e 15 à direita) da palavra "fogo" (também intercambiáveis) toda vez que aparece. Quero ver cada palavra e o número de vezes que aparece neste período de 15 palavras para cada instância de "fogo". Então, por exemplo, "fogo" é usado 3 vezes. Dessas três vezes, a palavra "luz" cai dentro de 15 palavras de cada lado duas vezes. Gostaria de uma tabela que mostre a palavra, o número de vezes que ela aparece na proximidade especificada de 15, a distância máxima (que neste caso é 12), a distância mínima (que é 7) e a distância média (que é 9,5).
Imaginei que precisaria de várias etapas e pacotes para fazer isso funcionar. Meu primeiro pensamento foi usar a função "kwic" da quanteda, pois permite escolher uma "janela" em torno de um termo específico. Então, uma contagem de termos com base nos resultados kwic não é tão difícil (com as palavras-chave removidas para a frequência, mas não para a medida de proximidade das palavras). Meu problema real é encontrar as distâncias máxima, mínima e média do termo de foco e, em seguida, colocar os resultados em uma boa tabela organizada com os termos como linhas em ordem decrescente por frequência e as colunas, fornecendo a contagem de frequência, distância máxima e mínimo distância e distância média.
Aqui está o que eu tenho até agora:
library(quanteda)
library(tm)
mysong <- char_tolower(song)
toks <- tokens(mysong, remove_hyphens = TRUE, remove_punct = TRUE,
remove_numbers = TRUE, remove_symbols = TRUE)
mykwic <- kwic(toks, "fire", window = 15, valuetype ="fixed")
thekwic <- as.character(mykwic)
thekwic <- removePunctuation(thekwic)
thekwic <- removeNumbers(thekwic)
thekwic <- removeWords(thekwic, stopwords("en"))
kwicFreq <- termFreq(thekwic)
Qualquer ajuda é muito apreciada.